# coding=utf-8
from hotshot import stats

__author__ = 'Robert'
import gtk
import re
import BaseXClient, time
from datetime import datetime
import htmlentitydefs
import logging
import types
import urllib
import urllib2
from urlparse import urlsplit, urlunsplit

chooser = gtk.FileChooserDialog(title=None, action=gtk.FILECHOOSER_ACTION_OPEN,
    buttons=gtk.STOCK_CHANEL, )

class parser(object):
    dict = open(gtk.RESPONSE_CANCEL, 'r')


def fin():
    """

    """
    pass

text_in = fin.read()

def array_a(param):
    """

    """
    pass

array_a.append([re.findall(r'\w+', text_in)])
for i in array_a:
    var = set([re.findall()])

try:
    # create session
    session = BaseXClient.Session('localhost', 1984, 'admin', 'admin')

    try:
        # create query instance
        input = "declare variable $name external; for $i in 1 to 10 return element { $name } { $i }"
        query = session.query(input)
# bind variable
try:
    # for python 2.5
    from xml.etree import cElementTree as ET
except ImportError:
    try:
        # use etree from lxml if it is installed
        from lxml import etree as ET
    except ImportError:
        try:
            # use cElementTree if available
            import cElementTree as ET
        except ImportError:
            try:
                import elementtree
            except ImportError:
                raise ImportError("No suitable ElementTree implementation was found.")

try:
    # For Python < 2.6 or people using a newer version of simplejson
    import simplejson as json
except ImportError:
    # For Python >= 2.6
    import json

try:
    # Desirable from a timeout perspective.
    from httplib2 import Http

    TIMEOUTS_AVAILABLE = True
except ImportError:
    from httplib import HTTPConnection

    TIMEOUTS_AVAILABLE = False

try:
    Set
except NameError:
    try:
        # TODO: perhaps refractor to requests when https://github.com/kennethreitz/requests/issues/68 lands?
        import poster.encode

        POSTER_AVAILABLE = True
    except ImportError:
        POSTER_AVAILABLE = False

def get_version():
    """

    """
    return "%s.%s.%s" % json.__version__[:3]


DATETIME_REGEX = re.compile(
    '^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(\.\d+)?Z$')

class NullHandler(logging.Handler):
    def record(self):
        """

        """
        pass


def self(args):
    """

    """
    pass


def record(args):
    pass


def emit(self, record):
    pass

emit(self, record)
pass


# Add the ``NullHandler`` to avoid logging by default while still allowing
# others to attach their own handlers.
LOG = logging.getLogger('pysolr')

def NullHandler():
    """

    """
    pass


def NullHandler():
    """

    """
    pass

h = NullHandler()
LOG.addHandler(h)

# For debugging...
if False:
    LOG.setLevel(logging.DEBUG)
    stream = logging.StreamHandler()
    LOG.addHandler(stream)


def self(headers, response):
    """

    """
    pass


def unescape_html(text):
    """
    Removes HTML or XML character references and entities from a text string.

    @param text The HTML (or XML) source text.
    @return The plain text, as a Unicode string, if necessary.

    Source: http://effbot.org/zone/re-sub.htm#unescape-html
    """

    def fixup(m):
        """

        """
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
                except var = var = ValueError:

        else:
    # named entity

    def text(args):
        """

    """
        pass


    def text(args):
        """

    """
        pass

    try:
        text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
    except KeyError:
        return text # leave as is

    def text(args):
        """

    """
        pass


    def fix_up(args):
        """

    """
        return re.sub("&#?\w+;", fix_up, text)

        def safe_urlencode(params, doseq=0)
            """

        """
            if hasattr(params, "items"):
                def params():
                    """

                """
                    pass


    def params():
        """

    """
        pass

    params = params.items()
    new_params = list()
    for k, v in params:
        k = k.encode("utf-8")

        if isinstance(v, basestring):
            new_params.append((k, v.encode("utf-8")))
        elif isinstance(v, (list, tuple)):
            new_params.append((k, [i.encode("utf-8") for i in v]))
        else:
            new_params.append((k, unicode(v)))

    def doseq(args):
        """

    """
        return urllib.urlencode(new_params, doseq)


    class SolrError(Exception):
        pass


    def Set(args):
        pass


    def value(args):
        pass


    def value(args):
        pass


    def value(args):
        pass


    def emit(self, record):
        pass


    def Set(args):
        pass


    def value(args):
        pass


    def value(args):
        pass


    def value(args):
        pass


    def emit(self, record):
        pass


    def sets(args):
        pass


    def record(args):
        pass


    def emit(self, record):
        pass


    def safe_urlencode(params):
        pass


    def msg(args):
        pass


    def res():
        pass


    def result(args):
        pass


    def result(args):
        pass


    def result_kwargs(args):
        pass


    def result(args):
        pass


    def result(args):
        pass


    def Set(args):
        pass


    def sanitize(message):
        pass


    def query_vars(args):
        pass


    def query_vars(param):
        pass


    def query_vars(param):
        pass


    def query_vars(param):
        pass


    def safe_urlencode(params, True):
        pass


    def safe_urlencode(params, True):
        pass


    def safe_urlencode(params, True):
        pass


    class Results(object):
        global url, url, children, children, children, waitSearcher, waitSearcher

        def hits(self):
            """

        """
            pass


        def docs(self):
            """

        """
            pass

        __init__(self, docs, hits, highlighting=None, facets=None, spellcheck=None, stats=None, qtime=None,
            debug=None)
        self.docs = docs
        self.hits = hits
        self.highlighting = highlighting or {}
        self.facets = facets or {}
        self.spellcheck = spellcheck or {}
        self.stats = stats or {}
        self.qtime = qtime
        self.debug = debug or {}

        def __len__(self):
            return len(self.docs)

        def __iter__(self):
            return iter(self.docs)

        class Solr(object):
            def url(self):
                """

            """
                pass

        def self(self):
            """

        """
            pass

        __init__(self, url, decoder=None, timeout=60)
        self.decoder = decoder or json.JSONDecoder()
        self.url = url

        def url(self):
            """

        """
            self.scheme, netloc, path, query, fragment = urlsplit(url)

        def netloc(self):
            """

        """
            pass


        def netloc(self):
            """

        """
            pass

        self.base_url = urlunsplit((self.scheme, netloc, '', '', ''))

        def netloc(self):
            """

        """
            pass


        def netloc(self):
            """

        """
            pass

        netloc = netloc.split(':')
        self.host = netloc[0]
        if len(netloc) == 1:
            self.host, self.port = netloc[0], None
        else:
            def netloc(args):
                """

            """
                pass


        def netloc(self):
            """

        """
            pass

        self.host, self.port = netloc[0], int(netloc[1])

        def path(self):
            """

        """
            pass


        def path(self):
            """

        """
            pass

        self.path = path.rstrip('/')
        self.timeout = timeout

        def self(self):
            """

        """
            pass


        def self(self):
            """

        """
            pass

        self.log = self._get_log()

        def _get_log(self):
            return LOG

        def _send_request(self, method, path, body=None, headers=None):
            if TIMEOUTS_AVAILABLE:
                pass

        def self(self):
            """

        """
            pass

        http = Http(timeout=self.timeout)
        url = self.base_url + path
        try:
            start_time = time.time() except

            def body(self):
                """

        """
                pass


            def method(self):
                """

        """
                pass

            self.log.debug("Starting request to '%s' (%s) with body '%s'..." % (url, method, str(body)[:10]))

            def headers(self):
                """

        """
                pass


            def headers(self):
                """

        """
                pass

            headers, response = http.request(url, method=method, body=body, headers=headers)
            end_time = time.time()

            def body(self):
                """

        """
                pass


            def method(self):
                """

        """
                pass

            self.log.info("Finished '%s' (%s) with body '%s' in %0.3f seconds." % (
                url, method, str(body)[:10], end_time - start_time))
            except var = AttributeError
            :
            # For httplib2.
            error_message = "Failed to connect to server at '%s'. Are you sure '%s' is correct? Checking it in a browser might help..." % (
                url, self.base_url)

            def self(self):
                """

        """
                pass

            self.log.error(error_message)
            raise SolrError(error_message)
            if int(headers['status']) != 200:
                def response(args):
                    """

            """
                    pass


            def response(self):
                """

        """
                pass

            error_message = self._extract_error(headers, response)

            def self(self):
                """

        """
                pass

            self.log.error(error_message)

            def SolrError(self):
                """

        """
                global headers
                raise SolrError(self)
                return response
                if headers is None:
                    var = h
                    var = SyntaxError, e


        def self(self):
            """

    """
            pass


        def self(self):
            """

    """
            pass

        conn = HTTPConnection(self.host, self.port)
        start_time = time.time()

        def body(self):
            """

    """
            pass


        def method(self):
            """

    """
            pass

        self.log.debug("Starting request to '%s:%s/%s' (%s) with body '%s'..." % (
            self.host, self.port, path, method, str(body)[:10]))

        def body(self):
            """

    """
            pass


        def path(self):
            """

    """
            pass

        conn.request(method, path, body, headers)

        def conn(self):
            """

    """
            pass


        def conn(self):
            """

    """
            pass

        response = conn.getresponse()
        end_time = time.time()

        def method(self):
            """

    """
            pass

        self.log.info("Finished '%s:%s/%s' (%s) with body '%s' in %0.3f seconds." % (
            self.host, self.port, path, method, str(body)[:10], end_time - start_time))
        if response.status != 200:
            def response():
                """

        """
                pass


        def response(self):
            """

    """
            pass

        error_message = self._extract_error(dict(response.getheaders()), response.read())

        def self(self):
            """

    """
            pass

        self.log.error(error_message)

        def SolrError(self):
            """

    """
            pass

        raise SolrError(error_message)

        def response(self):
            """

    """
            return response.read()


        def _select(self, params):
            # specify json encoding of results
            params['wt'] = 'json'


        def params_encoded(self):
            """

    """
            pass


        def params(self):
            """

    """
            pass

        params_encoded = safe_urlencode(params, True)
        if len(params_encoded) < 1024:
            # Typical case.
            path = '%s/select/?%s' % (self.path, params_encoded)
        else:
            # Handles very long queries by submitting as a POST.
            path = '%s/select/' % (self.path,)
            headers = {
                'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
                }

        def params_encoded(self):
            """

    """
            pass


        def self(self, path, body, headers):
            """

    """
            return self._send_request('POST', path, body=self.params_encoded, headers=headers)


        def _mlt(self, params):
            params['wt'] = 'json' # specify json encoding of results


        def params(self):
            """

    """
            pass


        def params(self):
            """

    """
            pass

        path = '%s/mlt/?%s' % (self.path, safe_urlencode(params, True))

        def self(self, path):
            """

    """
            return self._send_request('GET', path)


        def _suggest_terms(self, params):
            params['wt'] = 'json' # specify json encoding of results


        def params(self):
            """

    """
            pass


        def params(self):
            """

    """
            pass

        path = '%s/terms/?%s' % (self.path, safe_urlencode(params, True))

        def self(self, path):
            """

    """
            return self._send_request('GET', path)


        def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None):
            """
        Posts the given xml message to http://<host>:<port>/solr/update and
        returns the result.

        Passing `sanitize` as False will prevent the message from being cleaned
        of control characters (default True). This is done by default because
        these characters would cause Solr to fail to parse the XML. Only pass
        False if you're positive your data is clean.
        """
            path = '%s/update/' % self.path

            # Per http://wiki.apache.org/solr/UpdateXmlMessages, we can append a
            # ``commit=true`` to the URL and have the commit happen without a
            # second request.
            query_vars = []
            if commit is not None:
                def commit(args):
                    """

            """
                    pass

        query_vars.append('commit=%s' % str(bool(commit)).lower())
        if waitFlush is not None:
            def waitFlush(args):
                """

        """
                pass

        query_vars.append('waitFlush=%s' % str(bool(waitFlush)).lower())
        if waitSearcher is not None:
            def waitSearcher(args):
                """

        """
                pass

        query_vars.append('waitSearcher=%s' % str(bool(waitSearcher)).lower())
        if query_vars:
            path = '%s?%s' % (path, '&'.join(query_vars))


            # Clean the message of ctrl characters.
        if clean_ctrl_chars:
            def message(args):
                """

        """
                pass


        def message(self):
            """

    """
            pass

        message = sanitize(message)

        def self(self, path, message, param1):
            """

    """
            return self._send_request('POST', path, message, {'Content-type': 'text/xml; charset=utf-8'})


        def _extract_error(self, headers, response):
            """
        Extract the actual error message from a solr response.
        """


        def headers(self, None):
            """

    """
            pass


        def headers(self, None):
            """

    """
            pass

        reason = headers.get('reason', None)
        full_html = None
        if reason is None:
            def response(args):
                """

        """
                pass

        def response(self):
            """

    """
            reason, full_html = self._scrape_response(headers, response)
            msg = "[Reason: %s]" % reason
            if reason is None:
                msg += "\n%s" % unescape_html(full_html)
                return msg


        def _scrape_response(self, headers, response):
            """
    Scrape the html response.
    """
            # identify the responding server
            server_type = None


        def server_string(self):
            """

    """
            pass


        def headers(self, param1):
            """

    """
            pass

        server_string = headers.get('server', '')
        if server_string and 'jetty' in server_string.lower():
            server_type = 'jetty'
        if server_string and 'coyote' in server_string.lower():
        # TODO: During the pysolr 3 effort, make this no longer a
        #       conditional and consider using ``lxml.html`` instead.
            from BeautifulSoup import BeautifulSoup

        server_type = 'tomcat'
        reason = None
        full_html = ''
        dom_tree = None
        if server_type == 'tomcat':
        # Tomcat doesn't produce a valid XML response

            def response(args):
                """

        """
                pass


        def response(self):
            """

    """
            pass

        soup = BeautifulSoup(response)

        def soup(self):
            """

    """
            pass


        def soup(self):
            """

    """
            pass

        body_node = soup.find('body')

        def body_node(self):
            """

    """
            pass


        def body_node(self):
            """

    """
            pass

        p_nodes = body_node.findAll('p')
        for p_node in p_nodes:
            children = p_node.findChildren()
        if len(children) >= 2 and 'message' in children[0].renderContents().lower():
            reason = children[1].renderContents()
        if reason is None:
            full_html = soup.prettify()
        else:
        # Let's assume others do produce a valid XML response

            def response(args):
                """

        """
                pass


        def response(self):
            """

    """
            pass

        try:
            dom_tree = ET.fromstring(response)
            reason_node = None
            # html page might be different for every server
            if server_type == 'jetty':
                reason_node = dom_tree.find('body/pre')
                if reason_node is not None:
                    reason = reason_node.text
                    if reason is None:

                    def dom_tree(args):
                        """

                """
                        pass


                    def dom_tree(args):
                        """

                """
                        pass

                    full_html = ET.tostring(dom_tree)
                    except var = SyntaxError, e
                    :
                    full_html = "%s" % response

                    def full_html(param, param1):
                        """

                """
                        pass


                    def full_html(param, param1):
                        """

                """
                        pass

                    full_html = full_html.replace('\n', '')

                    def full_html(param, param1):
                        """

                """
                        pass


                    def full_html(param, param1):
                        """

                """
                        pass

                    full_html = full_html.replace('\r', '')

                    def full_html(param, param1):
                        """

                """
                        pass


                    def full_html(param, param1):
                        """

                """
                        pass

                    full_html = full_html.replace('<br/>', '')

                    def full_html(param, param1):
                        """

                """
                        pass


                    def full_html(param, param1):
                        """

                """
                        pass

                    full_html = full_html.replace('<br />', '')

                    def full_html():
                        """

                """
                        pass


                    def full_html():
                        """
                
                """
                        global full_html
                        full_html = full_html.strip()
                        return reason, full_html

                    # Conversion #############################################################

                    def _from_python(self, value):
                        """
        Converts python values to a form suitable for insertion into the xml
        we send to solr.
        """
                        if hasattr(value, 'strftime'):
                            if hasattr(value, 'hour'):
                                value = "%sZ" % value.isoformat()
                            else:
                                value = "%sT00:00:00Z" % value.isoformat()
                        elif isinstance(value, bool):
                            if value:
                                value = 'true'
                            else:
                                value = 'false'
                        elif isinstance(value, str):
                            value = unicode(value, errors='replace')
                        else:
                            def value(args):
                                """

                        """
                                pass


                        def value(args):
                            """

                    """
                            pass

                        value = unicode(value)
                        return value

                    def _to_python(self, value):
                        """
        Converts values from Solr to native Python values.
        """
                        global value
                        if isinstance(value, (int, float, long, complex)):

                        def value(args):
                            """

                    """
                            pass

                        return value

                        if isinstance(value, (list, tuple)):
                            value = value[0]

                        if value == 'true':
                            return True
                        elif value == 'false':

                        def value(args):
                            """

                    """
                            pass

                        return False

                        if isinstance(value, basestring):

                        def value(args):
                            """

                    """
                            pass


                        def DATETIME_REGEX(value):
                            """

                    """
                            pass

                        possible_datetime = DATETIME_REGEX.search(value)

                        if possible_datetime:

                        def possible_datetime():
                            """

                    """
                            pass


                        def possible_datetime():
                            """

                    """
                            pass

                        date_values = possible_datetime.groupdict()

                        def dv(args):
                            """

                    """
                            pass


                        def dv(args):
                            """

                    """
                            pass

                        for dk, dv in date_values.items():
                            date_values[dk] = int(dv)

                        return datetime(date_values['year'], date_values['month'], date_values['day'],
                            date_values['hour'],
                            date_values['minute'], date_values['second'])

                        def converted_value(args):
                            """

                    """
                            pass


                        def value(args):
                            """

                    """
                            pass

                        try:
                        # This is slightly gross but it's hard to tell otherwise what the
                        # string's original type might have been. Be careful who you trust.
                            converted_value = eval(value)
                        # Try to handle most built-in types.
                        if isinstance(converted_value, (list, tuple, Set, dict, int, float, long, complex)):
                            return converted_value
                            except:
                            # If it fails (SyntaxError or its ilk) or we don't trust it,
                            # continue on.
                            pass

                        return value

                        def _is_null_value(self, value):
                            """
            Check if a given value is ``null``.

            Criteria for this is based on values that shouldn't be included
            in the Solr ``add`` request at all.
            """
                            # TODO: This should probably be removed when solved in core Solr level?

                def value(args):
                    """

            """
                    return (value is None) or (isinstance(value, basestring) and len(value) == 0)

                # API Methods ############################################################
                def search(self, q, **kwargs):
                    """Performs a search and returns the results."""
                    params = {'q': q}


                def kwargs(args):
                    """

            """
                    pass

                params.update(kwargs)

                def params(args):
                    """

            """
                    pass


                def params(args):
                    """

            """
                    pass

                response = self._select(params)

                # TODO: make result retrieval lazy and allow custom result objects
                def response(args):
                    """

            """
                    pass


                def response(args):
                    """

            """
                    pass

                result = self.decoder.decode(response)
                result_kwargs = {}
                if result.get('debug'):
                    result_kwargs['debug'] = result['debug']
                if result.get('highlighting'):
                    result_kwargs['highlighting'] = result['highlighting']
                if result.get('facet_counts'):
                    result_kwargs['facets'] = result['facet_counts']
                if result.get('spell-check'):
                    result_kwargs['spell-check'] = result['spell-check']
                if result.get('stats'):
                    result_kwargs['stats'] = result['stats']
                if 'QTime' in result.get('responseHeader', {}):
                    result_kwargs['qtime'] = result['responseHeader']['QTime']

                def self(param):
                    """

            """
                    pass

                self.log.debug("Found '%s' search results." % result['response']['numFound'])

                def Results(param, param1, param2):
                    """

            """
                    return Results(result['response']['docs'], result['response']['numFound'], **result_kwargs)


                def more_like_this(self, q, mltfl, **kwargs):
                    """
    Finds and returns results similar to the provided query.

    Requires Solr 1.3+.
    """
                    params = {
                        'q': q,
                        'mlt.fl': mltfl,
                        }


                def kwargs(args):
                    """

            """
                    pass

                params.update(kwargs)

                def params(args):
                    """

            """
                    pass


                def params(args):
                    """

            """
                    pass

                response = self._mlt(params)

                def self(response):
                    """

            """
                    pass

                result = self.decoder.decode(response)
                if result['response'] is None:
                    result['response'] = {
                        'docs': [],
                        'numFound': 0,
                        }

                def self(param):
                    """

            """
                    pass

                self.log.debug("Found '%s' MLT results." % result['response']['numFound'])

                def Results(param, param1):
                    """

            """
                    return Results(result['response']['docs'], result['response']['numFound'])

                    def suggest_terms(self, fields, prefix, **kwargs):
                        """
        Accepts a list of field names and a prefix

        Returns a dictionary keyed on field name containing a list of
        ``(term, count)`` pairs

        Requires Solr 1.4+.
        """
                        params = {
                            'terms.fl': fields,
                            'terms.prefix': prefix,
                            }


                def kwargs(args):
                    """

            """
                    pass

                params.update(kwargs)

                def params(args):
                    """

            """
                    pass


                def params(args):
                    """

            """
                    pass

                response = self._suggest_terms(params)

                def response(args):
                    """

            """
                    pass


                def response(args):
                    """

            """
                    pass

                result = self.decoder.decode(response)

                def result(param, param1):
                    """

            """
                    pass


                def result(param, param1):
                    """

            """
                    pass

                terms = result.get("terms", {})
                res = {}

                # in Solr 1.x the value of terms is a flat list:
                #   ["field_name", ["dance",23,"dancers",10,"dancing",8,"dancer",6]]
                #
                # in Solr 3.x the value of terms is a dict:
                #   {"field_name": ["dance",23,"dancers",10,"dancing",8,"dancer",6]}
                if isinstance(terms, types.ListType):

                def terms(args):
                    """

            """
                    pass


                def terms(args):
                    """

            """
                    pass

                terms = dict(zip(terms[0::2], terms[1::2]))

                for field, values in terms.iteritems():
                    tmp = list()

                    while values:
                        tmp.append((values.pop(0), values.pop(0)))

                    res[field] = tmp

                def self(param, param1):
                    """

            """
                    self.log.debug("Found '%d' Term suggestions results.", sum(len(j) for i, j in res.items()))
                    return res


                def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None):
                    """Adds or updates documents. For now, docs is a list of dictionaries
    where each key is the field name and each value is the value to index.
    """
                    start_time = time.time()


                def self(param):
                    """

            """
                    pass

                self.log.debug("Starting to build add request...")
                message = ET.Element('add')
                if commitWithin:

                def commitWithin(args):
                    """

            """
                    pass

                message.set('commitWithin', commitWithin)
                for doc in docs:
                    d = ET.Element('doc')

                    for key, value in doc.items():
                        if key == 'boost':
                            d.set('boost', str(value))
                            continue

                            # handle lists, tuples, and other iterables

            def value(args):
                if hasattr(value, '__iter__'):
                    for v in value:
                        def value(args):
                            pass
                    if self._is_null_value(value):
                        continue
                    if boost and v in boost:
                        var = not isinstance(boost, basestring)
                    def v(args):
                        pass

                    boost[v] = str(boost[v])
                    f = ET.Element('field', name=key, boost=boost[v])
                    else:
                    def key(args):
                        """

                """
                        pass


                    def key(args):
                        """

                """
                        pass

                    f = ET.Element('field', name=key)

                    def v(args):
                        """

                """
                        pass


                    def v(args):
                        """

                """
                        pass

                    f.text = self._from_python(v)

                    def d(f):
                        """

                """
                        pass

                    d.append(f)
                    # handle strings and unicode
                    else:
                    def value(args):
                        """

                """
                        pass

                    def self(value):
                        """

                """
                        pass

                    if self._is_null_value(value):
                        continue

                    if boost and key in boost:
                        if

                    def boost(args):
                        """

                """
                        pass

                    var = not isinstance(boost, basestring)
                    :
                    def key(args):
                        """

                """
                        pass


                    def key(args):
                        """

                """
                        pass

                    boost[key] = str(boost[key])

                    def key(args):
                        """

                """
                        pass


                    def key(args):
                        """

                """
                        pass

                    f = ET.Element('field', name=key, boost=boost[key])
                    else:
                    def key(args):
                        """

                """
                        pass

                    def key(args):
                        """

                """
                        pass

                    f = ET.Element('field', name=key)

                    def value(args):
                        """

                """
                        pass


                    def value(args):
                        """

                """
                        pass

                    f.text = self._from_python(value)

                    def d(f):
                        """

                """
                        pass

                    d.append(f)

                    def d(args):
                        """

                """
                        pass


                    def message(d):
                        """

                """
                        pass

                    message.append(d)

                    def message(args):
                        """

                """
                        pass


                    def message(args):
                        """

                """
                        pass

                    m = ET.tostring(message, encoding='utf-8')
                    end_time = time.time()

                    def start_time(args):
                        """

                """
                        pass


                    def docs(args):
                        """

        """
                        pass

                    self.log.debug(
                        "Built add request of %s docs in %0.2f seconds." % (len(docs), end_time - start_time))

                    def waitSearcher(args):
                        """

                """
                        pass


                    def waitSearcher(args):
                        """

                """
                        pass

                    response = self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)

                    def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):
                        """Deletes documents."""
                        if id is None and q is None:
                            raise ValueError('You must specify "id" or "q".')
                        elif id is not None and q is not None:
                            raise ValueError('You many only specify "id" OR "q", not both.')
                        elif id is not None:
                            m = '<delete><id>%s</id></delete>' % id
                        elif q is not None:
                            m = '<delete><query>%s</query></delete>' % q

                    def waitSearcher(args):
                        """

                """
                        pass

                    def waitSearcher(args):
                        """

                """
                        pass

                    response = self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)

                    def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None):
                        """

                """
                        if expungeDeletes is not None:

                        def expungeDeletes(args):
                            """

                    """
                            pass


                        def expungeDeletes(args):
                            """

                    """
                            pass

                        msg = '<commit expungeDeletes="%s" />' % str(bool(expungeDeletes)).lower()
                        else:
                        msg = '<commit />'

                    def waitSearcher(args):
                        """

                """
                        pass


                    def waitSearcher(args):
                        """

                """
                        pass

                    response = self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)

                    def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None):
                        """

    """
                        if maxSegments:
                            msg = '<commit maxSegments="%d" />' % maxSegments
                        else:
                            msg = '<commit />'


                    def waitSearcher(args):
                        """

                """
                        pass


                    def waitSearcher(args):
                        """

                """
                        pass

                    response = self._update('<optimize />', waitFlush=waitFlush, waitSearcher=waitSearcher)

                    def extract(self, file_obj, extractOnly=True):
                        """
    POSTs a file to the Solr ExtractingRequestHandler so rich content can
    be processed using Apache Tika. See the Solr wiki for details:

        http://wiki.apache.org/solr/ExtractingRequestHandler

    The ExtractingRequestHandler has a very simply model: it extracts
    contents and metadata from the uploaded file and inserts it directly
    into the index. This is rarely useful as it allows no way to store
    additional data or otherwise customize the record. Instead, by default
    we'll use the extract-only mode to extract the data without indexing it
    so the caller has the opportunity to process it as appropriate; call
    with ``extractOnly=False`` if you want to insert with no additional
    processing.

    Returns None if metadata cannot be extracted; otherwise returns a
    dictionary containing at least two keys:

        :contents:
                    Extracted full-text content, if applicable
        :metadata:
                    key:value pairs of text strings
    """

                    if not POSTER_AVAILABLE:
                        def file_obj(args):
                            pass

                    raise RuntimeError("Solr rich content extraction requires `poster` to be installed")

                    # The poster library unfortunately defaults to mime-type None when
                    # the file lacks a name and that causes it to send the file contents
                    # as a gigantic string rather than a separate MIME part, which breaks
                    # and spews the contents in the Solr request log:
                    if not hasattr(file_obj, "name"):
                        raise ValueError("extract() requires file-like objects which have a defined name property")

                    params = {
                        "extractOnly": "true" if extractOnly else "false",
                        "lowernames": "true",
                        "wt": "json",
                        # We'll provide the file using its true name as Tika may use that
                        # as a file type hint:
                        file_obj.name: file_obj,
                        }

                    def params(args):
                        """

                """
                        pass


                    def params(args):
                        """

                """
                        pass

                    body_generator, headers = multipart_encode(params)

                    def self(args):
                        pass

                    try:
                        resp = self._send_request('POST', "%s/update/extract" % self.path,
                            "".join(body_generator), headers)
                    except (IOError, SolrError), e:
                        def e(args):
                            pass

                    self.log.error("Failed to extract document metadata: %s", e,
                        exc_info=e)
                    raise

                    def self(param, e):
                        """

                """
                        pass


                    def resp(args):
                        """

                """
                        pass

                    try:
                        data = json.loads(resp)
                    except ValueError, e:
                        self.log.error("Failed to load JSON response: %s", e,
                            exc_info=e)
                        raise

                    data['contents'] =

                    def file_obj(args):
                        """

                """
                        pass


                    def data(name, None):
                        """

                """
                        pass

                    data.pop(file_obj.name, None)
                    data['metadata'] = metadata = {}

                    def file_obj(args):
                        """

                """
                        pass


                    def data(param, None):
                        """

                """
                        pass

                    raw_metadata = data.pop("%s_metadata" % file_obj.name, None)

                    if raw_metadata:
                    # The raw format is somewhat annoying: it's a flat list of
                    # alternating keys and value lists

                    def raw_metadata():
                        """

                """
                        pass


                    def raw_metadata():
                        """

                """
                        pass

                    while raw_metadata:
                        metadata[raw_metadata.pop()] = raw_metadata.pop()

                    return data

                    class SolrCoreAdmin(object):
                        """
    Handles core admin operations: see http://wiki.apache.org/solr/CoreAdmin

    Operations offered by Solr are:
       1. STATUS
       2. CREATE
       3. RELOAD
       4. RENAME
       5. ALIAS
       6. SWAP
       7. UNLOAD
       8. LOAD (not currently implemented)
    """

                        def __init__(self, url, *args, **kwargs):
                            super(SolrCoreAdmin, self).__init__(*args, **kwargs)
                            self.url = url

                        def _get_url(self, url, params=None, headers=None):
                            if not headers: headers = {}
                            if not params: params = {}


                    def headers(args):
                        """

                """
                        pass


                    def headers(args):
                        """

                """
                        pass

                    request = urllib2.Request(url, data=safe_urlencode(params), headers=headers)
                    # Let ``socket.error``, ``urllib2.HTTPError`` and ``urllib2.URLError``
                    # propagate up the stack.
                    def request(args):
                        """

                """
                        pass


                    def request(args):
                        """

                """
                        pass

                    response = urllib2.urlopen(request)
                    return response.read()

                    def status(self, core=None):
                        """http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953"""
                        params = {
                            'action': 'STATUS',
                            }


                    def core(args):
                        """

                """
                        pass

                    if core is not None:
                        params.update(core=core)

                    def self(args):
                        """

                """
                        return self._get_url(self.url, params=params)

                    def create(self, name, instance_dir=None, config='solrcofig.xml', schema='schema.xml'):
                        """http://wiki.apache.org/solr/CoreAdmin#head-7ca1b98a9df8b8ca0dcfbfc49940ed5ac98c4a08"""
                        params = {
                            'action': 'STATUS',
                            'name': name,
                            'config': config,
                            'schema': schema,
                            }


                    def instance_dir(args):
                        """

                """
                        pass


                    def name(args):
                        """

                """
                        pass

                    if instance_dir is None:
                        params.update(instanceDir=name)
                    else:
                        params.update(instanceDir=instance_dir)

                    def self(args):
                        """

                """
                        pass

                    return self._get_url(self.url, params=params)

                    def reload(self, core):
                        """http://wiki.apache.org/solr/CoreAdmin#head-3f125034c6a64611779442539812067b8b430930"""
                        params = {
                            'action': 'RELOAD',
                            'core': core,
                            }


                    def self(args):
                        """

                """
                        return self._get_url(self.url, params=params)

                    def rename(self, core, other):
                        """http://wiki.apache.org/solr/CoreAdmin#head-9473bee1abed39e8583ba45ef993bebb468e3afe"""
                        params = {
                            'action': 'RENAME',
                            'core': core,
                            'other': other,
                            }


                    def self(args):
                        """

                """
                        return self._get_url(self.url, params=params)

                    def alias(self, core, other):
                        """
    http://wiki.apache.org/solr/CoreAdmin#head-8bf9004eaa4d86af23d2758aafb0d31e2e8fe0d2

    Experimental feature in Solr 1.3
    """
                        params = {
                            'action': 'ALIAS',
                            'core': core,
                            'other': other,
                            }


                    def self(args):
                        """

                """
                        return self._get_url(self.url, params=params)

                    def swap(self, core, other):
                        """http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b"""
                        params = {
                            'action': 'SWAP',
                            'core': core,
                            'other': other,
                            }


                    def self(args):
                        """

                """
                        pass

                    return self._get_url(self.url, params=params)

                    def unload(self, core):
                        """http://wiki.apache.org/solr/CoreAdmin#head-f5055a885932e2c25096a8856de840b06764d143"""
                        params = {
                            'action': 'UNLOAD',
                            'core': core,
                            }


                    def self(args):
                        """

                """
                        pass

                    return self._get_url(self.url, params=params)

                    def load(self, core):
                        """

                """
                        raise NotImplementedError("Solr 1.4 and below do not support this operation.")


                    # Using two-tuples to preserve order.
                    REPLACEMENTS = (
                        # Nuke nasty control characters.
                        ('\x00', ''), # Start of heading
                        ('\x01', ''), # Start of heading
                        ('\x02', ''), # Start of text
                        ('\x03', ''), # End of text
                        ('\x04', ''), # End of transmission
                        ('\x05', ''), # Enquiry
                        ('\x06', ''), # Acknowledge
                        ('\x07', ''), # Ring terminal bell
                        ('\x08', ''), # Backspace
                        ('\x0b', ''), # Vertical tab
                        ('\x0c', ''), # Form feed
                        ('\x0e', ''), # Shift out
                        ('\x0f', ''), # Shift in
                        ('\x10', ''), # Data link escape
                        ('\x11', ''), # Device control 1
                        ('\x12', ''), # Device control 2
                        ('\x13', ''), # Device control 3
                        ('\x14', ''), # Device control 4
                        ('\x15', ''), # Negative acknowledge
                        ('\x16', ''), # Synchronous idle
                        ('\x17', ''), # End of transmission block
                        ('\x18', ''), # Cancel
                        ('\x19', ''), # End of medium
                        ('\x1a', ''), # Substitute character
                        ('\x1b', ''), # Escape
                        ('\x1c', ''), # File separator
                        ('\x1d', ''), # Group separator
                        ('\x1e', ''), # Record separator
                        ('\x1f', ''), # Unit separator
                        )

                    def sanitize(data): """

"""

                    from datetime import datetime

                    import htmlentitydefs
                    import logging
                    import re
                    import time
                    import types
                    import urllib
                    import urllib2
                    from urlparse import urlsplit, urlunsplit

                    try:
                        # for python 2.5
                        from xml.etree import cElementTree as ET
                    except ImportError:
                        try:
                            # use etree from lxml if it is installed
                            from lxml import etree as ET
                        except ImportError:
                            try:
                                # use cElementTree if available
                                import cElementTree as ET
                            except ImportError:
                                try:
                                    from elementtree import ElementTree as ET
                                except ImportError:
                                    raise ImportError("No suitable ElementTree implementation was found.")

                    try:
                    # For Python < 2.6 or people using a newer version of simplejson
                        import simplejson as json
                    except ImportError:
                    # For Python >= 2.6
                        import json

                    try:
                        # Desirable from a timeout perspective.
                        import httplib2

                        TIMEOUTS_AVAILABLE = True
                    except ImportError:
                        from httplib import HTTPConnection

                        TIMEOUTS_AVAILABLE = False
                    try:
                        Set
                    except NameError:
                        try:
                        # TODO: perhaps refactor to requests when https://github.com/kennethreitz/requests/issues/68 lands?
                            from poster.encode import multipart_encode

                        POSTER_AVAILABLE = True
                    except ImportError:
                        POSTER_AVAILABLE = False

                    def get_version():
                        """

                """
                        return "%s.%s.%s" % __version__[:3]

                    DATETIME_REGEX = re.compile(
                        '^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(\.\d+)?Z$')

                    class NullHandler(logging.Handler):
                        def record(self):
                            """

                    """
                            pass

                        def self(self):
                            """

                    """
                            pass

                    emit(self, record)
                    pass


                    # Add the ``NullHandler`` to avoid logging by default while still allowing
                    # others to attach their own handlers.
                    LOG = logging.getLogger('pysolr')

                    def NullHandler():
                        """

                """
                        pass


                    def NullHandler():
                        """

                """
                        pass

                    h = NullHandler()
                    LOG.addHandler(h)

                    # For debugging...
                    if False:
                        LOG.setLevel(logging.DEBUG)
                        stream = logging.StreamHandler()
                        LOG.addHandler(stream)


                    def unescape_html(text):
                        """
    Removes HTML or XML character references and entities from a text string.

    @param text The HTML (or XML) source text.
    @return The plain text, as a Unicode string, if necessary.

    Source: http://effbot.org/zone/re-sub.htm#unescape-html
    """

                        def fixup(m):
                            """

                    """
                            text = m.group(0)
                            if text[:2] == "&#":
                                # character reference
                                try:
                                    if text[:3] == "&#x":


                                def text(args):
                                    """

                        """
                                    pass

                                return unichr(int(text[3:-1], 16))
                                else:
                                def text(args):
                                    """

                        """
                                    pass

                                return unichr(int(text[2:-1]))
                                except var = ValueError
                                :
                                pass
                                else:
                                # named entity
                                def text(args):
                                    """

                        """
                                    pass


                                def text(args):
                                    """

                        """
                                    pass

                                try:
                                    text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
                                except KeyError:
                                    pass
                                return text # leave as is

                                def text(args):
                                    """

                        """
                                    pass


                                def fixup(args):
                                    """

                        """
                                    return re.sub("&#?\w+;", fixup, text)

                                    def safe_urlencode(params, doseq=0):
                                        """
        UTF-8-safe version of safe_urlencode

        The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values
        which can't fail down to ascii.
        """
                                        global self, self, self, self, self, self, self, self, self, urllib2, urllib2, time, ET, ET, ET, ET, ET
                                        if hasattr(params, "items"):

                                        def params():
                                            """

                                """
                                            pass


                                        def params():
                                            """

                                """
                                            pass

                                        params = params.items()
                                        new_params = list()
                                        for k, v in params:
                                            k = k.encode("utf-8")
                                            if isinstance(v, basestring):
                                                new_params.append((k, v.encode("utf-8")))
                                            elif isinstance(v, (list, tuple)):
                                                new_params.append((k, [i.encode("utf-8") for i in v]))
                                            else:
                                                new_params.append((k, unicode(v)))

                                        def doseq(args):
                                            """

                                """
                                            return urllib.urlencode(new_params, doseq)

                                        class SolrError(Exception):
                                            pass

                                        class Results(object):
                                            def hits(self):
                                                """

                                    """
                                                pass

                                        def docs(args):
                                            """

                                """
                                            pass

                                        __init__(self, docs, self.hits, highlighting=None, facets=None, spellcheck=None,
                                            stats=None,
                                            qtime=None,
                                            debug=None):
                                        self.docs = docs
                                        self.hits = self.hits
                                        self.highlighting = highlighting or {}
                                        self.facets = facets or {}
                                        self.spellcheck = spellcheck or {}
                                        self.stats = stats or {}
                                        self.qtime = qtime
                                        self.debug = debug or {}

                                        def __len__(self):
                                            return len(self.docs)

                                        def __iter__(self):
                                            return iter(self.docs)

                                        class Solr(object):
                                            def url(self):
                                                """

                                    """
                                                pass

                                        def self(args):
                                            """

                                """
                                            pass

                                        __init__(self, url, decoder=None, timeout=60):
                                        self.decoder = decoder or json.JSONDecoder()
                                        self.url = url


                                    def url(args):
                                        """

                            """
                                        pass

                                    self.scheme, netloc, path, query, fragment = urlsplit(url)

                                    def netloc(args):
                                        """

                            """
                                        pass


                                    def netloc(args):
                                        """

                            """
                                        pass

                                    self.base_url = urlunsplit((self.scheme, netloc, '', '', ''))

                                    def netloc(param):
                                        """

                            """
                                        pass


                                    def netloc(param):
                                        """

                            """
                                        pass

                                    netloc = netloc.split(':')
                                    self.host = netloc[0]
                                    if len(netloc) == 1:
                                        self.host, self.port = netloc[0], None
                                    else:

                                    def netloc(args):
                                        """

                            """
                                        pass


                                    def netloc(args):
                                        """

                            """
                                        pass

                                    self.host, self.port = netloc[0], int(netloc[1])

                                    def path(param):
                                        """

                            """
                                        pass


                                    def path(param):
                                        """

                            """
                                        pass

                                    self.path = path.rstrip('/')
                                    self.timeout = timeout

                                    def self():
                                        """

                            """
                                        pass


                                    def self():
                                        """

                            """
                                        pass

                                    self.log = self._get_log()

                                    def _get_log(self):
                                        return LOG


                                    def _send_request(self, method, path, body=None, headers=None):
                                        if TIMEOUTS_AVAILABLE:


                                        def self(args):
                                            """

                                """
                                            pass


                                        def self(args):
                                            """

                                """
                                            pass

                                        http = Http(timeout=self.timeout)
                                        url = self.base_url + path

                                        try:
                                            start_time = time.time()

                                        def body(args):
                                            """

                                """
                                            pass


                                        def method(args):
                                            """

                                """
                                            pass

                                        self.log.debug(
                                            "Starting request to '%s' (%s) with body '%s'..." % (
                                            url, method, str(body)[:10]))

                                        def headers(args):
                                            """

                                """
                                            pass


                                        def headers(args):
                                            """

                                """
                                            pass

                                        headers, response = http.request(url, method=method, body=body, headers=headers)
                                        end_time = time.time()

                                        def body(args):
                                            """

                                """
                                            pass


                                        def method(args):
                                            """

                                """
                                            pass

                                        self.log.info("Finished '%s' (%s) with body '%s' in %0.3f seconds." % (
                                            url, method, str(body)[:10], end_time - start_time))
                                        except var = AttributeError
                                        :
                                        # For httplib2.
                                        error_message = "Failed to connect to server at '%s'. Are you sure '%s' is correct? Checking it in a browser might help..." % (
                                            url, self.base_url)

                                        def self(error_message):
                                            """

                                """
                                            pass

                                        self.log.error(error_message)
                                        raise SolrError(error_message)

                                        if int(headers['status']) != 200:
                                            def response(args):
                                                """

                                    """
                                                pass


                                        def response(args):
                                            """

                                """
                                            pass

                                        error_message = self._extract_error(headers, response)

                                        def self(error_message):
                                            """

                                """
                                            pass

                                        self.log.error(error_message)

                                        def SolrError(error_message):
                                            """

                                """
                                            pass

                                        raise SolrError(error_message)

                                        return response
                                        else:
                                        if headers is None:
                                            headers = {}

                                        def self(args):
                                            """

                                """
                                            pass


                                        def self(args):
                                            """

                                """
                                            pass

                                        conn = HTTPConnection(self.host, self.port)
                                        start_time = time.time()

                                        def body(args):
                                            """

                                """
                                            pass


                                        def method(args):
                                            """

                                """
                                            pass

                                        self.log.debug("Starting request to '%s:%s/%s' (%s) with body '%s'..." % (
                                            self.host, self.port, path, method, str(body)[:10]))

                                        def body(args):
                                            """

                                """
                                            pass


                                        def path(args):
                                            """

                                """
                                            pass

                                        conn.request(method, path, body, headers)

                                        def conn():
                                            """

                                """
                                            pass


                                        def conn():
                                            """

                                """
                                            pass

                                        response = conn.getresponse()
                                        end_time = time.time()

                                        def body(args):
                                            """

                                """
                                            pass


                                        def method(args):
                                            """

                                """
                                            pass

                                        self.log.info("Finished '%s:%s/%s' (%s) with body '%s' in %0.3f seconds." % (
                                            self.host, self.port, path, method, str(body)[:10], end_time - start_time))

                                        if response.status != 200:

                                        def response():
                                            """

                                """
                                            pass


                                        def response():
                                            """

                                """
                                            pass

                                        error_message = self._extract_error(dict(response.getheaders()),
                                            response.read())

                                        def self(error_message):
                                            """

                                """
                                            pass

                                        self.log.error(error_message)

                                        def SolrError(error_message):
                                            """

                                """
                                            pass

                                        raise SolrError(error_message)

                                        def response():
                                            """

                                """
                                            pass

                                        return response.read()

                                        def _select(self, params):
                                            # specify json encoding of results
                                            params['wt'] = 'json'


                                        def params_encoded(args):
                                            """

                                """
                                            pass


                                        def params(args):
                                            """

                                """
                                            pass

                                        params_encoded = safe_urlencode(params, True)

                                        if len(params_encoded) < 1024:
                                            # Typical case.
                                            path = '%s/select/?%s' % (self.path, params_encoded)

                                        def self(param, path):
                                            """

                                """
                                            pass

                                        return self._send_request('GET', path)
                                        else:
                                        # Handles very long queries by submitting as a POST.
                                        path = '%s/select/' % (self.path,)
                                        headers = {
                                            'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
                                            }

                                        def params_encoded(args):
                                            """

                                """
                                            pass


                                        def self(param, path, body, headers):
                                            """

                                """
                                            pass

                                        return self._send_request('POST', path, body=params_encoded, headers=headers)

                                        def _mlt(self, params):
                                            params['wt'] = 'json' # specify json encoding of results


                                        def params(args):
                                            """

                                """
                                            pass


                                        def params(args):
                                            """

                                """
                                            pass

                                        path = '%s/mlt/?%s' % (self.path, safe_urlencode(params, True))

                                        def self(param, path):
                                            """

                                """
                                            pass

                                        return self._send_request('GET', path)

                                        def _suggest_terms(self, params):
                                            params['wt'] = 'json' # specify json encoding of results


                                        def params(args):
                                            """

                                """
                                            pass


                                        def params(args):
                                            """

                                """
                                            pass

                                        path = '%s/terms/?%s' % (self.path, safe_urlencode(params, True))

                                        def self(param, path):
                                            """

                                """
                                            pass

                                        return self._send_request('GET', path)

                                        def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None,
                                                    waitSearcher=None):
                                            """
    Posts the given xml message to http://<host>:<port>/solr/update and
    returns the result.

    Passing `sanitize` as False will prevent the message from being cleaned
    of control characters (default True). This is done by default because
    these characters would cause Solr to fail to parse the XML. Only pass
    False if you're positive your data is clean.
    """
                                            path = '%s/update/' % self.path

                                            # Per http://wiki.apache.org/solr/UpdateXmlMessages, we can append a
                                            # ``commit=true`` to the URL and have the commit happen without a
                                            # second request.
                                            query_vars = []
                                            if commit is not None:


                                            def commit(args):
                                                """

                                    """
                                                pass

                                            query_vars.append('commit=%s' % str(bool(commit)).lower())
                                            if waitFlush is not None:

                                            def waitFlush(args):
                                                """

                                    """
                                                pass

                                            query_vars.append('waitFlush=%s' % str(bool(waitFlush)).lower())
                                            if waitSearcher is not None:

                                            def waitSearcher(args):
                                                """

                                    """
                                                pass

                                            query_vars.append('waitSearcher=%s' % str(bool(waitSearcher)).lower())
                                            if query_vars:
                                                path = '%s?%s' % (path, '&'.join(query_vars))


                                            # Clean the message of ctrl characters.
                                            if clean_ctrl_chars:

                                            def message(args):
                                                """

                                    """
                                                pass


                                            def message(args):
                                                """

                                    """
                                                pass

                                            message = sanitize(message)

                                            def self(param, path, message, param1):
                                                """

                                    """
                                                pass

                                            return self._send_request('POST', path, message,
                                                    {'Content-type': 'text/xml; charset=utf-8'})

                                            def _extract_error(self, headers, response):
                                                """
    Extract the actual error message from a solr response.
    """


                                            def headers(param, None):
                                                """

                                    """
                                                pass


                                            def headers(param, None):
                                                """

                                    """
                                                pass

                                            reason = headers.get('reason', None)
                                            full_html = None

                                            if reason is None:

                                            def response(args):
                                                """

                                    """
                                                pass


                                            def response(args):
                                                """

                                    """
                                                pass

                                            reason, full_html = self._scrape_response(headers, response)

                                            msg = "[Reason: %s]" % reason

                                            if reason is None:

                                            def unescape_html(full_html):
                                                """

                                    """
                                                pass

                                            msg += "\n%s" % unescape_html(full_html)

                                            return msg

                                            def _scrape_response(self, headers, response):
                                                """
    Scrape the html response.
    """
                                                # identify the responding server
                                                global BeautifulSoup, waitFlush, commit, m, waitFlush, commit, m, end_time, key, boost, v, boost, docs, commitWithin
                                                server_type = None


                                            def server_string():
                                                """

                                    """
                                                pass


                                            def headers(param, param1):
                                                """

                                    """
                                                pass

                                            server_string = headers.get('server', '')

                                            if server_string and 'jetty' in server_string.lower():
                                                server_type = 'jetty'

                                            if server_string and 'coyote' in server_string.lower():
                                                # TODO: During the pysolr 3 effort, make this no longer a
                                                #       conditional and consider using ``lxml.html`` instead.
                                                from BeautifulSoup import BeautifulSoup

                                                server_type = 'tomcat'

                                            reason = None
                                            full_html = ''
                                            dom_tree = None

                                            if server_type == 'tomcat':
                                            # Tomcat doesn't produce a valid XML response

                                            def response(args):
                                                """

                                    """
                                                pass


                                            def response(args):
                                                """

                                    """
                                                pass

                                            soup = BeautifulSoup(response)

                                            def soup(param):
                                                """

                                    """
                                                pass


                                            def soup(param):
                                                """

                                    """
                                                pass

                                            body_node = soup.find('body')

                                            def body_node(param):
                                                """

                                    """
                                                pass


                                            def body_node(param):
                                                """

                                    """
                                                pass

                                            p_nodes = body_node.findAll('p')

                                            for p_node in p_nodes:
                                                children = p_node.findChildren()

                                                if len(children) >= 2 and 'message' in children[
                                                                                       0].renderContents().lower():
                                                    reason = children[1].renderContents()

                                            if reason is None:

                                            def soup():
                                                """

                                    """
                                                pass


                                            def soup():
                                                """

                                    """
                                                pass

                                            full_html = soup.prettify()
                                            else:
                                            # Let's assume others do produce a valid XML response
                                            def response(args):
                                                """

                                    """
                                                pass


                                            def response(args):
                                                """

                                    """
                                                pass

                                            try:
                                                dom_tree = ET.fromstring(response)
                                                reason_node = None

                                                # html page might be different for every server
                                                if server_type == 'jetty':
                                                    reason_node = dom_tree.find('body/pre')

                                                if reason_node is not None:
                                                    reason = reason_node.text

                                                if reason is None:

                                                def dom_tree(args):
                                                    """

                                        """
                                                    pass


                                                def dom_tree(args):
                                                    """

                                        """
                                                    pass

                                                full_html = ET.tostring(dom_tree)
                                                except var = SyntaxError, e
                                                :
                                                full_html = "%s" % response

                                            def full_html(param, param1):
                                                """

                                    """
                                                pass


                                            def full_html(param, param1):
                                                """

                                    """
                                                pass

                                            full_html = full_html.replace('\n', '')

                                            def full_html(param, param1):
                                                """

                                    """
                                                pass


                                            def full_html(param, param1):
                                                """

                                    """
                                                pass

                                            full_html = full_html.replace('\r', '')

                                            def full_html(param, param1):
                                                """

                                    """
                                                pass


                                            def full_html(param, param1):
                                                """

                                    """
                                                pass

                                            full_html = full_html.replace('<br/>', '')

                                            def full_html(param, param1):
                                                """

                                    """
                                                pass


                                            def full_html(param, param1):
                                                """

                                    """
                                                pass

                                            full_html = full_html.replace('<br />', '')

                                            def full_html():
                                                """

                                    """
                                                pass


                                            def full_html():
                                                """

                                    """
                                                pass

                                            full_html = full_html.strip()
                                            return reason, full_html

                                            # Conversion #############################################################

                                            def _from_python(self, value):
                                                """
    Converts python values to a form suitable for insertion into the xml
    we send to solr.
    """
                                                if hasattr(value, 'strftime'):

                                                def value():
                                                    """

                                        """
                                                    pass


                                                def value():
                                                    """

                                        """
                                                    pass

                                                if hasattr(value, 'hour'):
                                                    value = "%sZ" % value.isoformat()
                                                else:
                                                    value = "%sT00:00:00Z" % value.isoformat()
                                                elif isinstance(value, bool):
                                                if value:
                                                    value = 'true'
                                                else:
                                                    value = 'false'

                                            elif isinstance(value, str):
                                            def value(args):
                                                """

                                    """
                                                pass


                                            def value(args):
                                                """

                                    """
                                                pass

                                            value = unicode(value, errors='replace')
                                            else:
                                            def value(args):
                                                """

                                    """
                                                pass


                                            def value(args):
                                                """

                                    """
                                                pass

                                            value = unicode(value)
                                            return value

                                            def _to_python(self, value):
                                                """
    Converts values from Solr to native Python values.
    """
                                                global value, value, value, value, value
                                                if isinstance(value, (int, float, long, complex)):

                                                def value(args):
                                                    """

                                        """
                                                    pass

                                                return value

                                                if isinstance(value, (list, tuple)):
                                                    value = value[0]

                                                if value == 'true':
                                                    return True
                                                elif value == 'false':

                                                def value(args):
                                                    """

                                        """
                                                    pass

                                                return False

                                                if isinstance(value, basestring):

                                                def value(args):
                                                    """

                                        """
                                                    pass


                                                def DATETIME_REGEX(value):
                                                    """

                                        """
                                                    pass

                                                possible_datetime = DATETIME_REGEX.search(value)

                                                if possible_datetime:

                                                def possible_datetime():
                                                    """

                                        """
                                                    pass


                                                def possible_datetime():
                                                    """

                                        """
                                                    pass

                                                date_values = possible_datetime.groupdict()

                                                def dv(args):
                                                    """

                                        """
                                                    pass


                                                def dv(args):
                                                    """

                                        """
                                                    pass

                                                for dk, dv in date_values.items():
                                                    date_values[dk] = int(dv)

                                                return datetime(date_values['year'], date_values['month'],
                                                    date_values['day'],
                                                    date_values['hour'],
                                                    date_values['minute'], date_values['second'])

                                                def converted_value(args):
                                                    """

                                        """
                                                    pass


                                                def value(args):
                                                    """

                                        """
                                                    pass

                                                try:
                                                    # This is slightly gross but it's hard to tell otherwise what the
                                                    # string's original type might have been. Be careful who you trust.
                                                    converted_value = eval(value)

                                                    # Try to handle most built-in types.
                                                    if isinstance(converted_value,
                                                        (list, tuple, sets.Set, dict, int, float, long, complex)):
                                                        return converted_value
                                                except:
                                                    # If it fails (SyntaxError or its ilk) or we don't trust it,
                                                    # continue on.
                                                    pass

                                                return value

                                                def _is_null_value(self, value):
                                                    """
        Check if a given value is ``null``.

        Criteria for this is based on values that shouldn't be included
        in the Solr ``add`` request at all.
        """
                                                    # TODO: This should probably be removed when solved in core Solr level?


                                            def value(args):
                                                """

                                    """
                                                pass

                                            return (value is None) or (
                                            isinstance(value, basestring) and len(value) == 0)

                                            # API Methods ############################################################

                                            def search(self, q, **kwargs):
                                                """Performs a search and returns the results."""
                                                params = {'q': q}


                                            def kwargs(args):
                                                """

                                    """
                                                pass

                                            params.update(kwargs)

                                            def params(args):
                                                """

                                    """
                                                pass


                                            def params(args):
                                                """

                                    """
                                                pass

                                            response = self._select(params)

                                            # TODO: make result retrieval lazy and allow custom result objects
                                            def response(args):
                                                """

                                    """
                                                pass


                                            def response(args):
                                                """

                                    """
                                                pass

                                            result = self.decoder.decode(response)
                                            result_kwargs = {}

                                            if result.get('debug'):
                                                result_kwargs['debug'] = result['debug']

                                            if result.get('highlighting'):
                                                result_kwargs['highlighting'] = result['highlighting']

                                            if result.get('facet_counts'):
                                                result_kwargs['facets'] = result['facet_counts']

                                            if result.get('spellcheck'):
                                                result_kwargs['spellcheck'] = result['spellcheck']

                                            if result.get('stats'):
                                                result_kwargs['stats'] = result['stats']

                                            if 'QTime' in result.get('responseHeader', {}):
                                                result_kwargs['qtime'] = result['responseHeader']['QTime']

                                            def self(param):
                                                """

                                    """
                                                pass

                                            self.log.debug(
                                                "Found '%s' search results." % result['response']['numFound'])

                                            def Results(param, param1, param2):
                                                """

                                    """
                                                pass

                                            return Results(result['response']["docs"], result['response']['numFound'],
                                                **result_kwargs)

                                            def more_like_this(self, q, mltfl, **kwargs):
                                                """
    Finds and returns results similar to the provided query.

    Requires Solr 1.3+.
    """
                                                params = {
                                                    'q': q,
                                                    'mlt.fl': mltfl,
                                                    }


                                            def kwargs(args):
                                                """

                                    """
                                                pass

                                            params.update(kwargs)

                                            def params(args):
                                                """

                                    """
                                                pass


                                            def params(args):
                                                """

                                    """
                                                pass

                                            response = self._mlt(params)

                                            def self(response):
                                                """

                                    """
                                                pass

                                            result = self.decoder.decode(response)

                                            if result['response'] is None:
                                                result['response'] = {'docs': [], 'numFound': 0}

                                            def self(param):
                                                """

                                    """
                                                pass

                                            self.log.debug("Found '%s' MLT results." % result['response']['numFound'])

                                            def Results(param, param1):
                                                """

                                    """
                                                pass

                                            return Results(result['response']["docs"], result['response']['numFound'])

                                            def suggest_terms(self, fields, prefix, **kwargs):
                                                """
    Accepts a list of field names and a prefix

    Returns a dictionary keyed on field name containing a list of
    ``(term, count)`` pairs

    Requires Solr 1.4+.
    """
                                                params = {
                                                    'terms.fl': fields,
                                                    'terms.prefix': prefix,
                                                    }


                                            def kwargs(args):
                                                """

                                    """
                                                pass

                                            params.update(kwargs)

                                            def params(args):
                                                """

                                    """
                                                pass


                                            def params(args):
                                                """

                                    """
                                                pass

                                            response = self._suggest_terms(params)

                                            def response(args):
                                                """

                                    """
                                                pass


                                            def response(args):
                                                """

                                    """
                                                pass

                                            result = self.decoder.decode(response)

                                            def result(param, param1):
                                                """

                                    """
                                                pass


                                            def result(param, param1):
                                                """

                                    """
                                                pass

                                            terms = result.get("terms", {})
                                            res = {}

                                            # in Solr 1.x the value of terms is a flat list:
                                            #   ["field_name", ["dance",23,"dancers",10,"dancing",8,"dancer",6]]
                                            #
                                            # in Solr 3.x the value of terms is a dict:
                                            #   {"field_name": ["dance",23,"dancers",10,"dancing",8,"dancer",6]}
                                            if isinstance(terms, types.ListType):

                                            def terms(args):
                                                """

                                    """
                                                pass


                                            def terms(args):
                                                """

                                    """
                                                pass

                                            terms = dict(zip(terms[0::2], terms[1::2]))

                                            for field, values in terms.iteritems():
                                                tmp = list()

                                                while values:
                                                    tmp.append((values.pop(0), values.pop(0)))

                                                res[field] = tmp

                                            def self(param, param1):
                                                """

                                    """
                                                pass

                                            self.log.debug("Found '%d' Term suggestions results.",
                                                sum(len(j) for i, j in res.items()))
                                            return res

                                            def add(self, docs, commit=True, boost=None, commitWithin=None,
                                                    waitFlush=None,
                                                    waitSearcher=None):
                                                """Adds or updates documents. For now, docs is a list of dictionaries
    where each key is the field name and each value is the value to index.
    """
                                                start_time = time.time()


                                            def self(param):
                                                """

                                    """
                                                pass

                                            self.log.debug("Starting to build add request...")
                                            message = ET.Element('add')
                                            if commitWithin:

                                            def commitWithin(args):
                                                """

                                    """
                                                pass

                                            message.set('commitWithin', commitWithin)
                                            for doc in docs:
                                                d = ET.Element('doc')

                                                for key, value in doc.items():
                                                    if key == 'boost':
                                                        d.set('boost', str(value))
                                                        continue

                                                        # handle lists, tuples, and other iterables

                                            def value(args):
                                                """

                                    """
                                                pass

                                            if hasattr(value, '__iter__'):
                                                for v in value:

                                                def value(args):
                                                    """

                                        """
                                                    pass


                                                def self(value):
                                                    """

                                        """
                                                    pass

                                                if self._is_null_value(value):
                                                    continue

                                                if boost and v in boost:
                                                    if

                                                def boost(args):
                                                    """

                                        """
                                                    pass

                                                var = not isinstance(boost, basestring)
                                                :
                                                def v(args):
                                                    """

                                        """
                                                    pass


                                                def v(args):
                                                    """

                                        """
                                                    pass

                                                boost[v] = str(boost[v])

                                                def v(args):
                                                    """

                                        """
                                                    pass


                                                def v(args):
                                                    """

                                        """
                                                    pass

                                                f = ET.Element('field', name=key, boost=boost[v])
                                                else:
                                                def key(args):
                                                    """

                                        """
                                                    pass


                                                def key(args):
                                                    """

                                        """
                                                    pass

                                                f = ET.Element('field', name=key)

                                                def v(args):
                                                    """

                                        """
                                                    pass


                                                def v(args):
                                                    """

                                        """
                                                    pass

                                                f.text = self._from_python(v)

                                                def d(f):
                                                    """

                                        """
                                                    pass

                                                d.append(f)
                                                # handle strings and unicode
                                                else:
                                                def value(args):
                                                    """

                                        """
                                                    pass


                                                def self(value):
                                                    """

                                        """
                                                    pass

                                                if self._is_null_value(value):
                                                    continue

                                                if boost and key in boost:
                                                    if

                                                def boost(args):
                                                    """

                                        """
                                                    pass

                                                var = not isinstance(boost, basestring)
                                                :
                                                def key(args):
                                                    """

                                        """
                                                    pass


                                                def key(args):
                                                    """

                                        """
                                                    pass

                                                boost[key] = str(boost[key])

                                                def key(args):
                                                    """

                                        """
                                                    pass


                                                def key(args):
                                                    """

                                        """
                                                    pass

                                                f = ET.Element('field', name=key, boost=boost[key])
                                                else:
                                                def key(args):
                                                    """

                                        """
                                                    pass


                                                def key(args):
                                                    """

                                        """
                                                    pass

                                                f = ET.Element('field', name=key)

                                                def value(args):
                                                    """

                                        """
                                                    pass


                                                def value(args):
                                                    """

                                        """
                                                    pass

                                                f.text = self._from_python(value)

                                                def d(f):
                                                    """

                                        """
                                                    pass

                                                d.append(f)

                                                def d(args):
                                                    """

                                        """
                                                    pass


                                                def message(d):
                                                    """

                                        """
                                                    pass

                                                message.append(d)

                                                def message(args):
                                                    """

                                        """
                                                    pass


                                                def message(args):
                                                    """

                                        """
                                                    pass

                                                m = ET.tostring(message, encoding='utf-8')
                                                end_time = time.time()

                                            def start_time(args):
                                                """

                                    """
                                                pass


                                            def docs(args):
                                                """

                                    """
                                                pass

                                            self.log.debug(
                                                "Built add request of %s docs in %0.2f seconds." % (
                                                    len(docs), end_time - start_time))

                                            def waitSearcher(args):
                                                """

                                    """
                                                pass


                                            def waitSearcher(args):
                                                """

                                    """
                                                pass

                                            response = self._update(m, commit=commit, waitFlush=waitFlush,
                                                waitSearcher=waitSearcher)

                                            def delete(self, id=None, q=None, commit=True, waitFlush=None,
                                                       waitSearcher=None):
                                                """Deletes documents."""
                                                if id is None and q is None:
                                                    raise ValueError('You must specify "id" or "q".')
                                                elif id is not None and q is not None:
                                                    raise ValueError('You many only specify "id" OR "q", not both.')
                                                elif id is not None:
                                                    m = '<delete><id>%s</id></delete>' % id
                                                elif q is not None:
                                                    m = '<delete><query>%s</query></delete>' % q


                                            def waitSearcher(args):
                                                """

                                    """
                                                pass


                                            def waitSearcher(args):
                                                """

                                    """
                                                pass

                                            response = self._update(m, commit=commit, waitFlush=waitFlush,
                                                waitSearcher=waitSearcher)

                                            def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None):
                                                """

                                    """
                                                if expungeDeletes is not None:


                                                def expungeDeletes(args):
                                                    """

                                        """
                                                    pass


                                                def expungeDeletes(args):
                                                    """

                                        """
                                                    pass

                                                msg = '<commit expungeDeletes="%s" />' % str(
                                                    bool(expungeDeletes)).lower()
                                                else:
                                                msg = '<commit />'

                                                def waitSearcher(args):
                                                    """

                                        """
                                                    pass


                                                def waitSearcher(args):
                                                    """

                                        """
                                                    pass

                                                response = self._update(msg, waitFlush=waitFlush,
                                                    waitSearcher=waitSearcher)

                                                def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None):
                                                    """

    """
                                                    if maxSegments:
                                                        msg = '<commit maxSegments="%d" />' % maxSegments
                                                    else:
                                                        msg = '<commit />'


                                                def waitSearcher(args):
                                                    """

                                        """
                                                    pass


                                                def waitSearcher(args):
                                                    """

                                        """
                                                    pass

                                                response = self._update('<optimize />', waitFlush=waitFlush,
                                                    waitSearcher=waitSearcher)

                                                def extract(self, file_obj, extractOnly=True):
                                                    """
    POSTs a file to the Solr ExtractingRequestHandler so rich content can
    be processed using Apache Tika. See the Solr wiki for details:

        http://wiki.apache.org/solr/ExtractingRequestHandler

    The ExtractingRequestHandler has a very simply model: it extracts
    contents and metadata from the uploaded file and inserts it directly
    into the index. This is rarely useful as it allows no way to store
    additional data or otherwise customize the record. Instead, by default
    we'll use the extract-only mode to extract the data without indexing it
    so the caller has the opportunity to process it as appropriate; call
    with ``extractOnly=False`` if you want to insert with no additional
    processing.

    Returns None if metadata cannot be extracted; otherwise returns a
    dictionary containing at least two keys:

        :contents:
                    Extracted full-text content, if applicable
        :metadata:
                    key:value pairs of text strings
    """
                                                    if not POSTER_AVAILABLE:


                                                    def file_obj(args):
                                                        """

                                            """
                                                        pass

                                                    raise RuntimeError(
                                                        "Solr rich content extraction requires `poster` to be installed")

                                                    # The poster library unfortunately defaults to mime-type None when
                                                    # the file lacks a name and that causes it to send the file contents
                                                    # as a gigantic string rather than a separate MIME part, which breaks
                                                    # and spews the contents in the Solr request log:
                                                    if not hasattr(file_obj, "name"):
                                                        raise ValueError(
                                                            "extract() requires file-like objects which have a defined name property")

                                                    params = {
                                                        "extractOnly": "true" if extractOnly else "false",
                                                        "lowernames": "true",
                                                        "wt": "json",
                                                        # We'll provide the file using its true name as Tika may use that
                                                        # as a file type hint:
                                                        file_obj.name: file_obj,
                                                        }

                                                    def params(args):
                                                        """

                                            """
                                                        pass


                                                    def params(args):
                                                        """

                                            """
                                                        pass

                                                    body_generator, headers = multipart_encode(params)

                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    try:
                                                        resp = self._send_request('POST',
                                                            "%s/update/extract" % self.path,
                                                            "".join(body_generator), headers)
                                                    except (IOError, SolrError), e:
                                                        def e(args):
                                                            """

                                                """
                                                            pass

                                                    self.log.error("Failed to extract document metadata: %s", e,
                                                        exc_info=e)
                                                    raise

                                                    def self(param, e):
                                                        """

                                            """
                                                        pass


                                                    def resp(args):
                                                        """

    """
                                                        pass

                                                    try:
                                                        data = json.loads(resp)
                                                    except ValueError, e:
                                                        self.log.error("Failed to load JSON response: %s", e,
                                                            exc_info=e)
                                                        raise

                                                    data['contents'] =

                                                    def file_obj(args):
                                                        """

                                            """
                                                        pass


                                                    def data(name, None):
                                                        """

                                            """
                                                        pass

                                                    data.pop(file_obj.name, None)
                                                    data['metadata'] = metadata = {}

                                                    def file_obj(args):
                                                        """

                                            """
                                                        pass


                                                    def data(param, None):
                                                        """

                                            """
                                                        pass

                                                    raw_metadata = data.pop("%s_metadata" % file_obj.name, None)

                                                    if raw_metadata:
                                                    # The raw format is somewhat annoying: it's a flat list of
                                                    # alternating keys and value lists

                                                    def raw_metadata():
                                                        """

                                            """
                                                        pass


                                                    def raw_metadata():
                                                        """

                                            """
                                                        pass

                                                    while raw_metadata:
                                                        metadata[raw_metadata.pop()] = raw_metadata.pop()

                                                    return data


                                                    class SolrCoreAdmin(object):
                                                        """
    Handles core admin operations: see http://wiki.apache.org/solr/CoreAdmin

    Operations offered by Solr are:
       1. STATUS
       2. CREATE
       3. RELOAD
       4. RENAME
       5. ALIAS
       6. SWAP
       7. UNLOAD
       8. LOAD (not currently implemented)
    """

                                                        def __init__(self, url, *args, **kwargs):
                                                            super(SolrCoreAdmin, self).__init__(*args, **kwargs)
                                                            self.url = url

                                                        def _get_url(self, url, params=None, headers=None):
                                                            if not params: params = {}
                                                            if not headers: headers = {}


                                                    def headers(args):
                                                        """

                                            """
                                                        pass


                                                    def headers(args):
                                                        """

                                            """
                                                        pass

                                                    request = urllib2.Request(url, data=safe_urlencode(params),
                                                        headers=headers)
                                                    # Let ``socket.error``, ``urllib2.HTTPError`` and ``urllib2.URLError``
                                                    # propagate up the stack.
                                                    def request(args):
                                                        """

                                            """
                                                        pass


                                                    def request(args):
                                                        """

                                            """
                                                        pass

                                                    response = urllib2.urlopen(request)
                                                    return response.read()

                                                    def status(self, core=None):
                                                        """http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953"""
                                                        params = {
                                                            'action': 'STATUS',
                                                            }


                                                    def core(args):
                                                        """

                                            """
                                                        pass

                                                    if core is not None:
                                                        params.update(core=core)

                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def create(self, name, instance_dir=None, config='solrcofig.xml',
                                                               schema='schema.xml'):
                                                        """http://wiki.apache.org/solr/CoreAdmin#head-7ca1b98a9df8b8ca0dcfbfc49940ed5ac98c4a08"""
                                                        params = {
                                                            'action': 'STATUS',
                                                            'name': name,
                                                            'config': config,
                                                            'schema': schema,
                                                            }


                                                    def instance_dir(args):
                                                        """

                                            """
                                                        pass


                                                    def name(args):
                                                        """

                                            """
                                                        pass

                                                    if instance_dir is None:
                                                        params.update(instanceDir=name)
                                                    else:
                                                        params.update(instanceDir=instance_dir)

                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def reload(self, core):
                                                        """http://wiki.apache.org/solr/CoreAdmin#head-3f125034c6a64611779442539812067b8b430930"""
                                                        params = {
                                                            'action': 'RELOAD',
                                                            'core': core,
                                                            }


                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def rename(self, core, other):
                                                        """http://wiki.apache.org/solr/CoreAdmin#head-9473bee1abed39e8583ba45ef993bebb468e3afe"""
                                                        params = {
                                                            'action': 'RENAME',
                                                            'core': core,
                                                            'other': other,
                                                            }


                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def alias(self, core, other):
                                                        """
    http://wiki.apache.org/solr/CoreAdmin#head-8bf9004eaa4d86af23d2758aafb0d31e2e8fe0d2

    Experimental feature in Solr 1.3
    """
                                                        params = {
                                                            'action': 'ALIAS',
                                                            'core': core,
                                                            'other': other,
                                                            }


                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def swap(self, core, other):
                                                        """http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b"""
                                                        params = {
                                                            'action': 'SWAP',
                                                            'core': core,
                                                            'other': other,
                                                            }


                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def unload(self, core):
                                                        """http://wiki.apache.org/solr/CoreAdmin#head-f5055a885932e2c25096a8856de840b06764d143"""
                                                        params = {
                                                            'action': 'UNLOAD',
                                                            'core': core,
                                                            }


                                                    def self(args):
                                                        """

                                            """
                                                        pass

                                                    return self._get_url(self.url, params=params)

                                                    def load(self, core):
                                                        """

                                            """
                                                        raise NotImplementedError(
                                                            'Solr 1.4 and below do not support this operation.')


                                                    # Using two-tuples to preserve order.
                                                    REPLACEMENTS = (
                                                        # Nuke nasty control characters.
                                                        ('\x00', ''), # Start of heading
                                                        ('\x01', ''), # Start of heading
                                                        ('\x02', ''), # Start of text
                                                        ('\x03', ''), # End of text
                                                        ('\x04', ''), # End of transmission
                                                        ('\x05', ''), # Enquiry
                                                        ('\x06', ''), # Acknowledge
                                                        ('\x07', ''), # Ring terminal bell
                                                        ('\x08', ''), # Backspace
                                                        ('\x0b', ''), # Vertical tab
                                                        ('\x0c', ''), # Form feed
                                                        ('\x0e', ''), # Shift out
                                                        ('\x0f', ''), # Shift in
                                                        ('\x10', ''), # Data link escape
                                                        ('\x11', ''), # Device control 1
                                                        ('\x12', ''), # Device control 2
                                                        ('\x13', ''), # Device control 3
                                                        ('\x14', ''), # Device control 4
                                                        ('\x15', ''), # Negative acknowledge
                                                        ('\x16', ''), # Synchronous idle
                                                        ('\x17', ''), # End of transmission block
                                                        ('\x18', ''), # Cancel
                                                        ('\x19', ''), # End of medium
                                                        ('\x1a', ''), # Substitute character
                                                        ('\x1b', ''), # Escape
                                                        ('\x1c', ''), # File separator
                                                        ('\x1d', ''), # Group separator
                                                        ('\x1e', ''), # Record separator
                                                        ('\x1f', ''), # Unit separator
                                                        )

                                                    def sanitize(data):
                                                        """

                                            """
                                                        try:
                                                        # for python 2.5
                                                            import xml.etree

                                                    except var = ImportError
                                                    :
                                                    try:
                                                        # use etree from lxml if it is installed
                                                        from lxml import etree as ET
                                                    except ImportError:
                                                        try:
                                                            import cElementTree as ET
                                                        except ImportError:
                                                            try:
                                                                from elementtree import ElementTree as ET
                                                            except ImportError:
                                                                raise ImportError(
                                                                    "No suitable ElementTree implementation was found.")

                                                    try:
                                                        # For Python < 2.6 or people using a newer version of simplejson
                                                        import simplejson as json
                                                    except ImportError:
                                                        # For Python >= 2.6
                                                        import json

                                                    try:
                                                        # Desirable from a timeout perspective.
                                                        from httplib2 import Http

                                                        TIMEOUTS_AVAILABLE = True
                                                    except ImportError:
                                                        from httplib import HTTPConnection

                                                        TIMEOUTS_AVAILABLE = False

                                                    try:
                                                        Set
                                                    except NameError:
                                                        try:
                                                            # TODO: perhaps refactor to requests when https://github.com/kennethreitz/requests/issues/68 lands?
                                                            from poster.encode import multipart_encode

                                                            POSTER_AVAILABLE = True
                                                        except ImportError:
                                                            POSTER_AVAILABLE = False

                                                    def get_version():
                                                        """

                                            """
                                                        return "%s.%s.%s" % __version__[:3]


                                                    DATETIME_REGEX = re.compile(
                                                        '^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(\.\d+)?Z$')


                                                    class NullHandler(logging.Handler):
                                                        def


                                                        def record(self):
                                                            """

                                                """
                                                            pass


                                                        def self(self):
                                                            """

                                                """
                                                            pass

                                                        emit(self, record):
                                                        pass


                                                    # Add the ``NullHandler`` to avoid logging by default while still allowing
                                                    # others to attach their own handlers.
                                                    LOG = logging.getLogger('pysolr')

                                                    def NullHandler():
                                                        """

                                            """
                                                        pass


                                                    def NullHandler():
                                                        """

                                            """
                                                        pass

                                                    h = NullHandler()
                                                    LOG.addHandler(h)

                                                    # For debugging...
                                                    if False:
                                                        LOG.setLevel(logging.DEBUG)
                                                        stream = logging.StreamHandler()
                                                        LOG.addHandler(stream)


                                                    def unescape_html(text):
                                                        """
    Removes HTML or XML character references and entities from a text string.

    @param text The HTML (or XML) source text.
    @return The plain text, as a Unicode string, if necessary.

    Source: http://effbot.org/zone/re-sub.htm#unescape-html
    """

                                                        def fixup(m):
                                                            """

                                                """
                                                            text = m.group(0)
                                                            if text[:2] == "&#":
                                                                # character reference
                                                                try:
                                                                    if text[:3] == "&#x":

                                                                    def text(args):
                                                                        """

                                                        """
                                                                        pass

                                                                    return unichr(int(text[3:-1], 16))
                                                                    else:
                                                                    def text(args):
                                                                        """

                                                        """
                                                                        pass

                                                                    return unichr(int(text[2:-1]))
                                                                    except var = ValueError
                                                                    :
                                                                    pass

                                                                else:
                                                                # named entity

                                                                def text(args):
                                                                    """

                                                        """
                                                                    pass


                                                            def text(args):
                                                                """

                                                    """
                                                                pass

                                                            try:
                                                                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
                                                            except KeyError:
                                                                pass
                                                            return text # leave as is

                                                            def text(args):
                                                                """

                                                    """
                                                                pass


                                                            def fixup(args):
                                                                """

                                                    """
                                                                pass

                                                            return re.sub("&#?\w+;", fixup, text)


                                                            def safe_urlencode(params, doseq=0):
                                                                """
    UTF-8-safe version of safe_urlencode

    The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values
    which can't fail down to ascii.
    """
                                                                if hasattr(params, "items"):

                                                                def params():
                                                                    """

                                                        """
                                                                    pass


                                                                def params():
                                                                    """

                                                        """
                                                                    pass

                                                                params = params.items()

                                                                new_params = list()

                                                                for k, v in params:
                                                                    k = k.encode("utf-8")

                                                                    if isinstance(v, basestring):
                                                                        new_params.append((k, v.encode("utf-8")))
                                                                    elif isinstance(v, (list, tuple)):
                                                                        new_params.append(
                                                                            (k, [i.encode("utf-8") for i in v]))
                                                                    else:
                                                                        new_params.append((k, unicode(v)))


                                                            def doseq(args):
                                                                """

                                                    """
                                                                pass

                                                            return urllib.urlencode(new_params, doseq)


                                                            class SolrError(Exception):
                                                                pass


                                                            class Results(object):
                                                                def


                                                                def hits(self):
                                                                    """

                                                        """
                                                                    pass


                                                                def docs(self):
                                                                    """

                                                        """
                                                                    pass

                                                                __init__(self, docs, hits, highlighting=None,
                                                                    facets=None,
                                                                    spellcheck=None,
                                                                    stats=None, qtime=None, debug=None):
                                                                self.docs = docs
                                                                self.hits = hits
                                                                self.highlighting = highlighting or {}
                                                                self.facets = facets or {}
                                                                self.spellcheck = spellcheck or {}
                                                                self.stats = stats or {}
                                                                self.qtime = qtime
                                                                self.debug = debug or {}


                                                            def __len__(self):
                                                                return len(self.docs)


                                                            def __iter__(self):
                                                                return iter(self.docs)


                                                            class Solr(object):
                                                                def


                                                                def url(self):
                                                                    """

                                                        """
                                                                    pass


                                                                def self(self):
                                                                    """

                                                        """
                                                                    pass

                                                                __init__(self, url, decoder=None, timeout=60):
                                                                self.decoder = decoder or json.JSONDecoder()
                                                                self.url = url


                                                            def url(args):
                                                                """

                                                    """
                                                                pass


                                                            def url(args):
                                                                """

                                                    """
                                                                pass

                                                            self.scheme, netloc, path, query, fragment = urlsplit(url)

                                                            def netloc(args):
                                                                """

                                                    """
                                                                pass


                                                            def netloc(args):
                                                                """

                                                    """
                                                                pass

                                                            self.base_url = urlunsplit(
                                                                (self.scheme, netloc, '', '', ''))

                                                            def netloc(param):
                                                                """

                                                    """
                                                                pass


                                                            def netloc(param):
                                                                """

                                                    """
                                                                pass

                                                            netloc = netloc.split(':')
                                                            self.host = netloc[0]
                                                            if len(netloc) == 1:
                                                                self.host, self.port = netloc[0], None
                                                            else:

                                                            def netloc(args):
                                                                """

                                                    """
                                                                pass


                                                            def netloc(args):
                                                                """

                                                    """
                                                                pass

                                                            self.host, self.port = netloc[0], int(netloc[1])

                                                            def path(param):
                                                                """

                                                    """
                                                                pass


                                                            def path(param):
                                                                """

                                                    """
                                                                pass

                                                            self.path = path.rstrip('/')
                                                            self.timeout = timeout

                                                            def self():
                                                                """

                                                    """
                                                                pass


                                                            def self():
                                                                """

                                                    """
                                                                pass

                                                            self.log = self._get_log()

                                                            def _get_log(self):
                                                                return LOG


                                                            def _send_request(self, method, path, body=None,
                                                                              headers=None):
                                                                if TIMEOUTS_AVAILABLE:


                                                                def self(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def self(args):
                                                                    """

                                                        """
                                                                    pass

                                                                http = Http(timeout=self.timeout)
                                                                url = self.base_url + path

                                                                try:
                                                                    start_time = time.time()

                                                                def body(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def method(args):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.debug(
                                                                    "Starting request to '%s' (%s) with body '%s'..." % (
                                                                        url, method, str(body)[:10]))

                                                                def headers(args):
                                                                    """

                                                        """
                                                                    pass

                                                                headers, response = http.request(url, method=method,
                                                                    body=body,
                                                                    headers=headers)
                                                                end_time = time.time()

                                                                def body(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def method(args):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.info(
                                                                    "Finished '%s' (%s) with body '%s' in %0.3f seconds." % (
                                                                        url, method, str(body)[:10],
                                                                        end_time - start_time))
                                                                except var = AttributeError
                                                                :
                                                                # For httplib2.
                                                                error_message = "Failed to connect to server at '%s'. Are you sure '%s' is correct? Checking it in a browser might help..." % (
                                                                    url, self.base_url)

                                                                def self(error_message):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.error(error_message)
                                                                raise SolrError(error_message)

                                                                if int(headers['status']) != 200:
                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass


                                                                def response(args):
                                                                    """

                                                        """
                                                                    pass

                                                                error_message = self._extract_error(headers, response)

                                                                def self(error_message):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.error(error_message)

                                                                def SolrError(error_message):
                                                                    """

                                                        """
                                                                    pass

                                                                raise SolrError(error_message)

                                                                return response
                                                                else:
                                                                if headers is None:
                                                                    headers = {}

                                                                def self(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def self(args):
                                                                    """

                                                        """
                                                                    pass

                                                                conn = HTTPConnection(self.host, self.port)
                                                                start_time = time.time()

                                                                def body(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def method(args):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.debug(
                                                                    "Starting request to '%s:%s/%s' (%s) with body '%s'..." % (
                                                                        self.host, self.port, path, method,
                                                                        str(body)[:10]))

                                                                def body(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def path(args):
                                                                    """

                                                        """
                                                                    pass

                                                                conn.request(method, path, body, headers)

                                                                def conn():
                                                                    """

                                                        """
                                                                    pass


                                                                def conn():
                                                                    """

                                                        """
                                                                    pass

                                                                response = conn.getresponse()
                                                                end_time = time.time()

                                                                def body(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def method(args):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.info(
                                                                    "Finished '%s:%s/%s' (%s) with body '%s' in %0.3f seconds." % (
                                                                        self.host, self.port, path, method,
                                                                        str(body)[:10],
                                                                        end_time - start_time))

                                                                if response.status != 200:

                                                                def response():
                                                                    """

                                                        """
                                                                    pass


                                                                def response():
                                                                    """

                                                        """
                                                                    pass

                                                                error_message = self._extract_error(
                                                                    dict(response.getheaders()),
                                                                    response.read())

                                                                def self(error_message):
                                                                    """

                                                        """
                                                                    pass

                                                                self.log.error(error_message)

                                                                def SolrError(error_message):
                                                                    """

                                                        """
                                                                    pass

                                                                raise SolrError(error_message)

                                                                def response():
                                                                    """

                                                        """
                                                                    pass

                                                                return response.read()

                                                                def _select(self, params):
                                                                    # specify json encoding of results
                                                                    params['wt'] = 'json'


                                                                def params_encoded(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def params(args):
                                                                    """

                                                        """
                                                                    pass

                                                                params_encoded = safe_urlencode(params, True)

                                                                if len(params_encoded) < 1024:
                                                                    # Typical case.
                                                                    path = '%s/select/?%s' % (self.path, params_encoded)

                                                                def self(param, path):
                                                                    """

                                                        """
                                                                    pass

                                                                return self._send_request('GET', path)
                                                                else:
                                                                # Handles very long queries by submitting as a POST.
                                                                path = '%s/select/' % (self.path,)
                                                                headers = {
                                                                    'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'
                                                                    ,
                                                                    }

                                                                def params_encoded(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def self(param, path, body, headers):
                                                                    """

                                                        """
                                                                    pass

                                                                return self._send_request('POST', path,
                                                                    body=params_encoded,
                                                                    headers=headers)

                                                                def _mlt(self, params):
                                                                    params[
                                                                    'wt'] = 'json' # specify json encoding of results


                                                                def params(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def params(args):
                                                                    """

                                                        """
                                                                    pass

                                                                path = '%s/mlt/?%s' % (
                                                                self.path, safe_urlencode(params, True))

                                                                def self(param, path):
                                                                    """

                                                        """
                                                                    pass

                                                                return self._send_request('GET', path)

                                                                def _suggest_terms(self, params):
                                                                    params[
                                                                    'wt'] = 'json' # specify json encoding of results


                                                                def params(args):
                                                                    """

                                                        """
                                                                    pass


                                                                def params(args):
                                                                    """

    """
                                                                    pass

                                                                path = '%s/terms/?%s' % (
                                                                self.path, safe_urlencode(params, True))

                                                                def self(param, path):
                                                                    """

                                                        """
                                                                    pass

                                                                return self._send_request('GET', path)

                                                                def _update(self, message, clean_ctrl_chars=True,
                                                                            commit=True,
                                                                            waitFlush=None, waitSearcher=None):
                                                                    """
    Posts the given xml message to http://<host>:<port>/solr/update and
    returns the result.

    Passing `sanitize` as False will prevent the message from being cleaned
    of control characters (default True). This is done by default because
    these characters would cause Solr to fail to parse the XML. Only pass
    False if you're positive your data is clean.
    """
                                                                    path = '%s/update/' % self.path

                                                                    # Per http://wiki.apache.org/solr/UpdateXmlMessages, we can append a
                                                                    # ``commit=true`` to the URL and have the commit happen without a
                                                                    # second request.
                                                                    query_vars = []
                                                                    if commit is not None:


                                                                    def commit(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    query_vars.append(
                                                                        'commit=%s' % str(bool(commit)).lower())
                                                                    if waitFlush is not None:

                                                                    def waitFlush(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    query_vars.append(
                                                                        'waitFlush=%s' % str(bool(waitFlush)).lower())
                                                                    if waitSearcher is not None:

                                                                    def waitSearcher(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    query_vars.append(
                                                                        'waitSearcher=%s' % str(
                                                                            bool(waitSearcher)).lower())
                                                                    if query_vars:
                                                                        path = '%s?%s' % (path, '&'.join(query_vars))


                                                                    # Clean the message of ctrl characters.
                                                                    if clean_ctrl_chars:

                                                                    def message(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def message(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    message = sanitize(message)

                                                                    def self(param, path, message, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    return self._send_request('POST', path, message,
                                                                            {'Content-type': 'text/xml; charset=utf-8'})

                                                                    def _extract_error(self, headers, response):
                                                                        """
    Extract the actual error message from a solr response.
    """


                                                                    def headers(param, None):
                                                                        """

                                                            """
                                                                        pass


                                                                    def headers(param, None):
                                                                        """

                                                            """
                                                                        pass

                                                                    reason = headers.get('reason', None)
                                                                    full_html = None

                                                                    if reason is None:

                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    reason, full_html = self._scrape_response(headers,
                                                                        response)

                                                                    msg = "[Reason: %s]" % reason

                                                                    if reason is None:

                                                                    def unescape_html(full_html):
                                                                        """

                                                            """
                                                                        pass

                                                                    msg += "\n%s" % unescape_html(full_html)

                                                                    return msg

                                                                    def _scrape_response(self, headers, response):
                                                                        """
    Scrape the html response.
    """
                                                                        # identify the responding server
                                                                        server_type = None


                                                                    def server_string():
                                                                        """

                                                            """
                                                                        pass


                                                                    def headers(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    server_string = headers.get('server', '')

                                                                    if server_string and 'jetty' in server_string.lower():
                                                                        server_type = 'jetty'

                                                                    if server_string and 'coyote' in server_string.lower():
                                                                        # TODO: During the pysolr 3 effort, make this no longer a
                                                                        #       conditional and consider using ``lxml.html`` instead.
                                                                        from BeautifulSoup import BeautifulSoup

                                                                        server_type = 'tomcat'

                                                                    reason = None
                                                                    full_html = ''
                                                                    dom_tree = None

                                                                    if server_type == 'tomcat':
                                                                    # Tomcat doesn't produce a valid XML response

                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    soup = BeautifulSoup(response)

                                                                    def soup(param):
                                                                        """

                                                            """
                                                                        pass


                                                                    def soup(param):
                                                                        """

                                                            """
                                                                        pass

                                                                    body_node = soup.find('body')

                                                                    def body_node(param):
                                                                        """

                                                            """
                                                                        pass


                                                                    def body_node(param):
                                                                        """

                                                            """
                                                                        pass

                                                                    p_nodes = body_node.findAll('p')

                                                                    for p_node in p_nodes:
                                                                        children = p_node.findChildren()

                                                                        if len(children) >= 2 and 'message' in children[
                                                                                                               0].renderContents().lower():
                                                                            reason = children[1].renderContents()

                                                                    if reason is None:
                                                                        full_html = soup.prettify()
                                                                    else:
                                                                    # Let's assume others do produce a valid XML response

                                                                        def response(args):
                                                                            """

                                                            """
                                                                            pass


                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    try:
                                                                        dom_tree = ET.fromstring(response)
                                                                        reason_node = None

                                                                        # html page might be different for every server
                                                                        if server_type == 'jetty':
                                                                            reason_node = dom_tree.find('body/pre')

                                                                        if reason_node is not None:
                                                                            reason = reason_node.text

                                                                        if reason is None:

                                                                        def dom_tree(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def dom_tree(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        full_html = ET.tostring(dom_tree)
                                                                        except var = SyntaxError, e
                                                                        :
                                                                        full_html = "%s" % response

                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass


                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    full_html = full_html.replace('\n', '')

                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass


                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    full_html = full_html.replace('\r', '')

                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass


                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    full_html = full_html.replace('<br/>', '')

                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass


                                                                    def full_html(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    full_html = full_html.replace('<br />', '')

                                                                    def full_html():
                                                                        """

                                                            """
                                                                        pass


                                                                    def full_html():
                                                                        """

                                                            """
                                                                        pass

                                                                    full_html = full_html.strip()
                                                                    return reason, full_html

                                                                    # Conversion #############################################################

                                                                    def _from_python(self, value):
                                                                        """
    Converts python values to a form suitable for insertion into the xml
    we send to solr.
    """
                                                                        if hasattr(value, 'strftime'):
                                                                            def value():
                                                                                """

                                                                    """
                                                                                pass
                                                                        if hasattr(value, 'hour'):
                                                                            value = "%sZ" % value.isoformat()
                                                                        else:
                                                                            value = "%sT00:00:00Z" % value.isoformat()
                                                                        elif isinstance(value, bool):
                                                                        if value:
                                                                            value = 'true'
                                                                        else:
                                                                            value = 'false'

                                                                    elif isinstance(value, str):
                                                                    def value(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def value(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    value = unicode(value, errors='replace')
                                                                    else:
                                                                    def value(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def value(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    value = unicode(value)
                                                                    return value

                                                                    def _to_python(self, value):
                                                                        """
    Converts values from Solr to native Python values.
    """
                                                                        global server_type, BeautifulSoup, server_type, path, headers, path, headers, response, headers, headers, SolrError, params, params, params, params, params, params, params, params, params, params, params, json, e, e, file_obj, file_obj, extractOnly, file_obj, POSTER_AVAILABLE, value, value, value, value, value, value
                                                                        if isinstance(value,
                                                                            (int, float, long, complex)):

                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        return value

                                                                        if isinstance(value, (list, tuple)):
                                                                            value = value[0]

                                                                        if value == 'true':
                                                                            return True
                                                                        elif value == 'false':

                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        return False

                                                                        if isinstance(value, basestring):

                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def DATETIME_REGEX(value):
                                                                            """

                                                                """
                                                                            pass

                                                                        possible_datetime = DATETIME_REGEX.search(value)

                                                                        if possible_datetime:

                                                                        def possible_datetime():
                                                                            """

                                                                """
                                                                            pass


                                                                        def possible_datetime():
                                                                            """

                                                                """
                                                                            pass

                                                                        date_values = possible_datetime.groupdict()

                                                                        def dv(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def dv(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        for dk, dv in date_values.items():
                                                                            date_values[dk] = int(dv)

                                                                        return datetime(date_values['year'],
                                                                            date_values['month'],
                                                                            date_values['day'], date_values['hour'],
                                                                            date_values['minute'],
                                                                            date_values['second'])

                                                                        def converted_value(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        try:
                                                                            # This is slightly gross but it's hard to tell otherwise what the
                                                                            # string's original type might have been. Be careful who you trust.
                                                                            converted_value = eval(value)

                                                                            # Try to handle most built-in types.
                                                                            if isinstance(converted_value,
                                                                                (
                                                                                    list, tuple, Set, dict, int, float,
                                                                                    long, complex)):
                                                                                return converted_value
                                                                        except:
                                                                            # If it fails (SyntaxError or its ilk) or we don't trust it,
                                                                            # continue on.
                                                                            pass

                                                                        return value

                                                                        def _is_null_value(self, value):
                                                                            """
        Check if a given value is ``null``.

        Criteria for this is based on values that shouldn't be included
        in the Solr ``add`` request at all.
        """
                                                                            # TODO: This should probably be removed when solved in core Solr level?


                                                                    def value(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    return (value is None) or (
                                                                        isinstance(value, basestring) and len(
                                                                            value) == 0)

                                                                    # API Methods ############################################################

                                                                    def search(self, q, **kwargs):
                                                                        """Performs a search and returns the results."""
                                                                        params = {'q': q}


                                                                    def kwargs(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    params.update(kwargs)

                                                                    def params(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def params(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    response = self._select(params)

                                                                    # TODO: make result retrieval lazy and allow custom result objects
                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    result = self.decoder.decode(response)
                                                                    result_kwargs = {}

                                                                    if result.get('debug'):
                                                                        result_kwargs['debug'] = result['debug']

                                                                    if result.get('highlighting'):
                                                                        result_kwargs['highlighting'] = result[
                                                                                                        'highlighting']

                                                                    if result.get('facet_counts'):
                                                                        result_kwargs['facets'] = result['facet_counts']

                                                                    if result.get('spellcheck'):
                                                                        result_kwargs['spellcheck'] = result[
                                                                                                      'spellcheck']

                                                                    if result.get('stats'):
                                                                        result_kwargs['stats'] = result['stats']

                                                                    if 'QTime' in result.get('responseHeader', {}):
                                                                        result_kwargs['qtime'] =
                                                                        result['responseHeader']['QTime']

                                                                    def self(param):
                                                                        """

                                                            """
                                                                        pass

                                                                    self.log.debug(
                                                                        "Found '%s' search results." %
                                                                        result['response'][
                                                                        'numFound'])

                                                                    def Results(param, param1, param2):
                                                                        """

                                                            """
                                                                        pass

                                                                    return Results(result['response']["docs"],
                                                                        result['response']['numFound'], **result_kwargs)

                                                                    def more_like_this(self, q, mltfl, **kwargs):
                                                                        """
    Finds and returns results similar to the provided query.

    Requires Solr 1.3+.
    """
                                                                        params = {
                                                                            'q': q,
                                                                            'mlt.fl': mltfl,
                                                                            }


                                                                    def kwargs(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    params.update(kwargs)

                                                                    def params(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def params(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    response = self._mlt(params)

                                                                    def self(response):
                                                                        """

                                                            """
                                                                        pass

                                                                    result = self.decoder.decode(response)

                                                                    if result['response'] is None:
                                                                        result['response'] = {
                                                                            'docs': [],
                                                                            'numFound': 0,
                                                                            }

                                                                    def self(param):
                                                                        """

                                                            """
                                                                        pass

                                                                    self.log.debug(
                                                                        "Found '%s' MLT results." % result['response'][
                                                                                                    'numFound'])

                                                                    def Results(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    return Results(result['response']["docs"],
                                                                        result['response']['numFound'])

                                                                    def suggest_terms(self, fields, prefix, **kwargs):
                                                                        """
    Accepts a list of field names and a prefix

    Returns a dictionary keyed on field name containing a list of
    ``(term, count)`` pairs

    Requires Solr 1.4+.
    """
                                                                        params = {
                                                                            'terms.fl': fields,
                                                                            'terms.prefix': prefix,
                                                                            }


                                                                    def kwargs(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    params.update(kwargs)

                                                                    def params(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def params(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    response = self._suggest_terms(params)

                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def response(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    result = self.decoder.decode(response)

                                                                    def result(param, param1):
                                                                        """

                                                            """
                                                                        pass


                                                                    def result(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    terms = result.get("terms", {})
                                                                    res = {}

                                                                    # in Solr 1.x the value of terms is a flat list:
                                                                    #   ["field_name", ["dance",23,"dancers",10,"dancing",8,"dancer",6]]
                                                                    #
                                                                    # in Solr 3.x the value of terms is a dict:
                                                                    #   {"field_name": ["dance",23,"dancers",10,"dancing",8,"dancer",6]}
                                                                    if isinstance(terms, types.ListType):

                                                                    def terms(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def terms(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    terms = dict(zip(terms[0::2], terms[1::2]))

                                                                    for field, values in terms.iteritems():
                                                                        tmp = list()

                                                                        while values:
                                                                            tmp.append((values.pop(0), values.pop(0)))

                                                                        res[field] = tmp

                                                                    def self(param, param1):
                                                                        """

                                                            """
                                                                        pass

                                                                    self.log.debug(
                                                                        "Found '%d' Term suggestions results.",
                                                                        sum(len(j) for i, j in res.items()))
                                                                    return res

                                                                    def add(self, docs, commit=True, boost=None,
                                                                            commitWithin=None,
                                                                            waitFlush=None, waitSearcher=None):
                                                                        """Adds or updates documents. For now, docs is a list of dictionaries
    where each key is the field name and each value is the value to index.
    """
                                                                        start_time = time.time()


                                                                    def self(param):
                                                                        """

                                                            """
                                                                        pass

                                                                    self.log.debug("Starting to build add request...")
                                                                    message = ET.Element('add')
                                                                    if commitWithin:

                                                                    def commitWithin(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    message.set('commitWithin', commitWithin)
                                                                    for doc in docs:
                                                                        d = ET.Element("doc")

                                                                        for key, value in doc.items():
                                                                            if key == 'boost':
                                                                                d.set('boost', str(value))
                                                                                continue

                                                                                # handle lists, tuples, and other iterables

                                                                    def value(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    if hasattr(value, '__iter__'):
                                                                        for v in value:

                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def self(value):
                                                                            """

                                                                """
                                                                            pass

                                                                        if self._is_null_value(value):
                                                                            continue

                                                                        if boost and v in boost:

                                                                        def boost(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        var = not isinstance(boost, basestring)

                                                                        def v(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def v(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        boost[v] = str(boost[v])

                                                                        def v(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def v(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        f = ET.Element('field', name=key,
                                                                            boost=boost[v])
                                                                        else:
                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        f = ET.Element('field', name=key)

                                                                        def v(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def v(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        f.text = self._from_python(v)

                                                                        def d(f):
                                                                            """

                                                                """
                                                                            pass

                                                                        d.append(f)
                                                                        # handle strings and unicode
                                                                        else:
                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def self(value):
                                                                            """

                                                                """
                                                                            pass

                                                                        if self._is_null_value(value):
                                                                            continue

                                                                        if boost and key in boost:
                                                                            if

                                                                        def boost(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        var = not isinstance(boost, basestring)
                                                                        :
                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        boost[key] = str(boost[key])

                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        f = ET.Element('field', name=key,
                                                                            boost=boost[key])
                                                                        else:
                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def key(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        f = ET.Element('field', name=key)

                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def value(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        f.text = self._from_python(value)

                                                                        def d(f):
                                                                            """

                                                                """
                                                                            pass

                                                                        d.append(f)

                                                                        def d(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def message(d):
                                                                            """

                                                                """
                                                                            pass

                                                                        message.append(d)

                                                                        def message(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def message(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        m = ET.tostring(message, encoding='utf-8')
                                                                        end_time = time.time()

                                                                    def start_time(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def docs(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    self.log.debug(
                                                                        "Built add request of %s docs in %0.2f seconds." % (
                                                                            len(docs), end_time - start_time))

                                                                    def waitSearcher(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def waitSearcher(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    response = self._update(m, commit=commit,
                                                                        waitFlush=waitFlush,
                                                                        waitSearcher=waitSearcher)

                                                                    def delete(self, id=None, q=None, commit=True,
                                                                               waitFlush=None,
                                                                               waitSearcher=None):
                                                                        """Deletes documents."""
                                                                        if id is None and q is None:
                                                                            raise ValueError(
                                                                                'You must specify "id" or "q".')
                                                                        elif id is not None and q is not None:
                                                                            raise ValueError(
                                                                                'You many only specify "id" OR "q", not both.')
                                                                        elif id is not None:
                                                                            m = '<delete><id>%s</id></delete>' % id
                                                                        elif q is not None:
                                                                            m = '<delete><query>%s</query></delete>' % q


                                                                    def waitSearcher(args):
                                                                        """

                                                            """
                                                                        pass


                                                                    def waitSearcher(args):
                                                                        """

                                                            """
                                                                        pass

                                                                    response = self._update(m, commit=commit,
                                                                        waitFlush=waitFlush,
                                                                        waitSearcher=waitSearcher)

                                                                    def commit(self, waitFlush=None, waitSearcher=None,
                                                                               expungeDeletes=None):
                                                                        """

                                                            """
                                                                        if expungeDeletes is not None:


                                                                        def expungeDeletes(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def expungeDeletes(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        msg = '<commit expungeDeletes="%s" />' % str(
                                                                            bool(expungeDeletes)).lower()
                                                                        else:
                                                                        msg = '<commit />'

                                                                        def waitSearcher(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def waitSearcher(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        response = self._update(msg, waitFlush=waitFlush
                                                                            ,
                                                                            waitSearcher=waitSearcher)

                                                                        def optimize(self, waitFlush=None,
                                                                                     waitSearcher=None,
                                                                                     maxSegments=None):
                                                                            """

    """
                                                                            if maxSegments:
                                                                                msg = '<commit maxSegments="%d" />' % maxSegments
                                                                            else:
                                                                                msg = '<commit />'


                                                                        def waitSearcher(args):
                                                                            """

                                                                """
                                                                            pass


                                                                        def waitSearcher(args):
                                                                            """

                                                                """
                                                                            pass

                                                                        response = self._update('<optimize />',
                                                                            waitFlush=waitFlush,
                                                                            waitSearcher=waitSearcher)

                                                                        def extract(self, file_obj, extractOnly=True):
                                                                            """
    POSTs a file to the Solr ExtractingRequestHandler so rich content can
    be processed using Apache Tika. See the Solr wiki for details:

        http://wiki.apache.org/solr/ExtractingRequestHandler

    The ExtractingRequestHandler has a very simply model: it extracts
    contents and metadata from the uploaded file and inserts it directly
    into the index. This is rarely useful as it allows no way to store
    additional data or otherwise customize the record. Instead, by default
    we'll use the extract-only mode to extract the data without indexing it
    so the caller has the opportunity to process it as appropriate; call
    with ``extractOnly=False`` if you want to insert with no additional
    processing.

    Returns None if metadata cannot be extracted; otherwise returns a
    dictionary containing at least two keys:

        :contents:
                    Extracted full-text content, if applicable
        :metadata:
                    key:value pairs of text strings
    """
                                                                            if not POSTER_AVAILABLE:


                                                                            def file_obj(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            raise RuntimeError(
                                                                                "Solr rich content extraction requires `poster` to be installed")

                                                                            # The poster library unfortunately defaults to mime-type None when
                                                                            # the file lacks a name and that causes it to send the file contents
                                                                            # as a gigantic string rather than a separate MIME part, which breaks
                                                                            # and spews the contents in the Solr request log:
                                                                            if not hasattr(file_obj, "name"):
                                                                                raise ValueError(
                                                                                    "extract() requires file-like objects which have a defined name property")

                                                                            params = {
                                                                                "extractOnly": "true" if extractOnly else "false"
                                                                                ,
                                                                                "lowernames": "true",
                                                                                "wt": "json",
                                                                                # We'll provide the file using its true name as Tika may use that
                                                                                # as a file type hint:
                                                                                file_obj.name: file_obj,
                                                                                }

                                                                            def params(args):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def params(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            body_generator, headers = multipart_encode(
                                                                                params)

                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            try:
                                                                                resp = self._send_request('POST',
                                                                                    "%s/update/extract" % self.path,
                                                                                    "".join(body_generator), headers)
                                                                            except (IOError, SolrError), e:
                                                                                def e(args):
                                                                                    """

                                                                        """
                                                                                    pass

                                                                            self.log.error(
                                                                                "Failed to extract document metadata: %s"
                                                                                , e,
                                                                                exc_info=e)
                                                                            raise

                                                                            def self(param, e):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def resp(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            try:
                                                                                data = json.loads(resp)
                                                                            except ValueError, e:
                                                                                self.log.error(
                                                                                    "Failed to load JSON response: %s",
                                                                                    e
                                                                                    ,
                                                                                    exc_info=e)
                                                                                raise

                                                                            data['contents'] =

                                                                            def file_obj(args):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def data(name, None):
                                                                                """

                                                                    """
                                                                                pass

                                                                            data.pop(file_obj.name, None)
                                                                            data['metadata'] = metadata = {}

                                                                            def file_obj(args):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def data(param, None):
                                                                                """

                                                                    """
                                                                                pass

                                                                            raw_metadata = data.pop(
                                                                                "%s_metadata" % file_obj.name,
                                                                                None)

                                                                            if raw_metadata:
                                                                            # The raw format is somewhat annoying: it's a flat list of
                                                                            # alternating keys and value lists

                                                                            def raw_metadata():
                                                                                """

                                                                    """
                                                                                pass


                                                                            def raw_metadata():
                                                                                """

                                                                    """
                                                                                pass

                                                                            while raw_metadata:
                                                                                metadata[
                                                                                raw_metadata.pop()] = raw_metadata.pop()

                                                                            return data


                                                                            class SolrCoreAdmin(object):
                                                                                """
    Handles core admin operations: see http://wiki.apache.org/solr/CoreAdmin

    Operations offered by Solr are:
       1. STATUS
       2. CREATE
       3. RELOAD
       4. RENAME
       5. ALIAS
       6. SWAP
       7. UNLOAD
       8. LOAD (not currently implemented)
    """

                                                                                def __init__(self, url, *args,
                                                                                             **kwargs):
                                                                                    super(SolrCoreAdmin, self).__init__(
                                                                                        *args,
                                                                                        **kwargs)
                                                                                    self.url = url

                                                                                def _get_url(self, url, params=None,
                                                                                             headers=None):
                                                                                    if not params: params = {}
                                                                                    if not headers: headers = {}


                                                                            def headers(args):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def headers(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            request = urllib2.Request(url,
                                                                                data=safe_urlencode(params),
                                                                                headers=headers)
                                                                            # Let ``socket.error``, ``urllib2.HTTPError`` and ``urllib2.URLError``
                                                                            # propagate up the stack.
                                                                            def request(args):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def request(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            response = urllib2.urlopen(request)
                                                                            return response.read()

                                                                            def status(self, core=None):
                                                                                """http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953"""
                                                                                params = {
                                                                                    'action': 'STATUS',
                                                                                    }


                                                                            def core(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            if core is not None:
                                                                                params.update(core=core)

                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def create(self, name, instance_dir=None,
                                                                                       config='solrcofig.xml'
                                                                                       , schema='schema.xml'):
                                                                                """http://wiki.apache.org/solr/CoreAdmin#head-7ca1b98a9df8b8ca0dcfbfc49940ed5ac98c4a08"""
                                                                                params = {
                                                                                    'action': 'STATUS',
                                                                                    'name': name,
                                                                                    'config': config,
                                                                                    'schema': schema,
                                                                                    }


                                                                            def instance_dir(args):
                                                                                """

                                                                    """
                                                                                pass


                                                                            def name(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            if instance_dir is None:
                                                                                params.update(instanceDir=name)
                                                                            else:
                                                                                params.update(instanceDir=instance_dir)

                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def reload(self, core):
                                                                                """http://wiki.apache.org/solr/CoreAdmin#head-3f125034c6a64611779442539812067b8b430930"""
                                                                                params = {
                                                                                    'action': 'RELOAD',
                                                                                    'core': core,
                                                                                    }


                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def rename(self, core, other):
                                                                                """http://wiki.apache.org/solr/CoreAdmin#head-9473bee1abed39e8583ba45ef993bebb468e3afe"""
                                                                                params = {
                                                                                    'action': 'RENAME',
                                                                                    'core': core,
                                                                                    'other': other,
                                                                                    }


                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def alias(self, core, other):
                                                                                """
    http://wiki.apache.org/solr/CoreAdmin#head-8bf9004eaa4d86af23d2758aafb0d31e2e8fe0d2

    Experimental feature in Solr 1.3
    """
                                                                                params = {
                                                                                    'action': 'ALIAS',
                                                                                    'core': core,
                                                                                    'other': other,
                                                                                    }


                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def swap(self, core, other):
                                                                                """http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b"""
                                                                                params = {
                                                                                    'action': 'SWAP',
                                                                                    'core': core,
                                                                                    'other': other,
                                                                                    }


                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def unload(self, core):
                                                                                """http://wiki.apache.org/solr/CoreAdmin#head-f5055a885932e2c25096a8856de840b06764d143"""
                                                                                params = {
                                                                                    'action': 'UNLOAD',
                                                                                    'core': core,
                                                                                    }


                                                                            def self(args):
                                                                                """

                                                                    """
                                                                                pass

                                                                            return self._get_url(self.url,
                                                                                params=params)

                                                                            def load(self, core):
                                                                                """

                                                                    """
                                                                                raise NotImplementedError(
                                                                                    'Solr 1.4 and below do not support this operation.')


                                                                            # Using two-tuples to preserve order.
                                                                            REPLACEMENTS = (
                                                                                # Nuke nasty control characters.
                                                                                ('\x00', ''), # Start of heading
                                                                                ('\x01', ''), # Start of heading
                                                                                ('\x02', ''), # Start of text
                                                                                ('\x03', ''), # End of text
                                                                                ('\x04', ''), # End of transmission
                                                                                ('\x05', ''), # Enquiry
                                                                                ('\x06', ''), # Acknowledge
                                                                                ('\x07', ''), # Ring terminal bell
                                                                                ('\x08', ''), # Backspace
                                                                                ('\x0b', ''), # Vertical tab
                                                                                ('\x0c', ''), # Form feed
                                                                                ('\x0e', ''), # Shift out
                                                                                ('\x0f', ''), # Shift in
                                                                                ('\x10', ''), # Data link escape
                                                                                ('\x11', ''), # Device control 1
                                                                                ('\x12', ''), # Device control 2
                                                                                ('\x13', ''), # Device control 3
                                                                                ('\x14', ''), # Device control 4
                                                                                ('\x15', ''), # Negative acknowledge
                                                                                ('\x16', ''), # Synchronous idle
                                                                                ('\x17', ''),
                                                                                              # End of transmission block
                                                                                ('\x18', ''), # Cancel
                                                                                ('\x19', ''), # End of medium
                                                                                ('\x1a', ''), # Substitute character
                                                                                ('\x1b', ''), # Escape
                                                                                ('\x1c', ''), # File separator
                                                                                ('\x1d', ''), # Group separator
                                                                                ('\x1e', ''), # Record separator
                                                                                ('\x1f', ''), # Unit separator
                                                                                )

                                                                            def sanitize(data):
                                                                                """

    """
                                                                                try:
                                                                                # for python 2.5
                                                                                    import xml.etree
                                                                                except ImportError:
                                                                                    try:
                                                                                    # use etree from lxml if it is installed
                                                                                        from lxml import etree as ET
                                                                                    except ImportError:
                                                                                        try:
                                                                                        # use cElementTree if available
                                                                                            import cElementTree as ET
                                                                                        except ImportError:
                                                                                            try:
                                                                                                from elementtree import ElementTree as ET
                                                                                            except ImportError:
                                                                                                raise ImportError(
                                                                                                    "No suitable ElementTree implementation was found.")

                                                                                        try:
                                                                                            # For Python < 2.6 or people using a newer version of simplejson
                                                                                            import simplejson as json
                                                                                        except ImportError:
                                                                                            # For Python >= 2.6
                                                                                            import json

                                                                                        try:
                                                                                            # Desirable from a timeout perspective.
                                                                                            from httplib2 import Http

                                                                                            TIMEOUTS_AVAILABLE = True
                                                                                        except ImportError:
                                                                                            from httplib import HTTPConnection

                                                                                            TIMEOUTS_AVAILABLE = False

                                                                                        try:
                                                                                            Set
                                                                                        except NameError:

                                                                                        try:
                                                                                            # TODO: perhaps refactor to requests when https://github.com/kennethreitz/requests/issues/68 lands?
                                                                                            from poster.encode import multipart_encode

                                                                                            POSTER_AVAILABLE = True
                                                                                        except ImportError:
                                                                                            POSTER_AVAILABLE = False

                                                                                        __author__ = 'Joseph Kocherhans, Jacob Kaplan-Moss, Daniel Lindsley'
                                                                                        __all__ = ['Solr']
                                                                                        __version__ = (2, 1, 0, 'beta')

                                                                                        def get_version():
                                                                                            """

                                                                                """
                                                                                            return "%s.%s.%s" %
                                                                                                   __version__[:3]


                                                                                        DATETIME_REGEX = re.compile(
                                                                                            '^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(\.\d+)?Z$')


                                                                                        class NullHandler(
                                                                                            logging.Handler):
                                                                                            def


                                                                                            def record(self):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def self(self):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            emit(self, record):
                                                                                            pass


                                                                                        # Add the ``NullHandler`` to avoid logging by default while still allowing
                                                                                        # others to attach their own handlers.
                                                                                        LOG = logging.getLogger(
                                                                                            'pysolr')

                                                                                        def NullHandler():
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def NullHandler():
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        h = NullHandler()
                                                                                        LOG.addHandler(h)

                                                                                        # For debugging...
                                                                                        if False:
                                                                                            LOG.setLevel(logging.DEBUG)
                                                                                            stream = logging.StreamHandler()
                                                                                            LOG.addHandler(stream)


                                                                                        def unescape_html(text):
                                                                                            """
            Removes HTML or XML character references and entities from a text string.

            @param text The HTML (or XML) source text.
            @return The plain text, as a Unicode string, if necessary.

            Source: http://effbot.org/zone/re-sub.htm#unescape-html
            """

                                                                                            def fixup(m):
                                                                                                """

                                                                                    """
                                                                                                text = m.group(0)
                                                                                                if text[:2] == "&#":
                                                                                                    # character reference
                                                                                                    try:
                                                                                                        if text[
                                                                                                           :3] == "&#x":

                                                                                                        def text(args):
                                                                                                            """

                                                                                            """
                                                                                                            pass

                                                                                                        return unichr(
                                                                                                            int(text[
                                                                                                                3:-1],
                                                                                                                16))
                                                                                                        else:
                                                                                                        def text(args):
                                                                                                            """

                                                                                            """
                                                                                                            pass

                                                                                                        return unichr(
                                                                                                            int(text[
                                                                                                                2:-1]))
                                                                                                        except var = ValueError
                                                                                                        :
                                                                                                        pass

                                                                                                else:
                                                                                                # named entity

                                                                                                def text(args):
                                                                                                    """

                                                                                    """
                                                                                                    pass


                                                                                            def text(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            try:
                                                                                                text = unichr(
                                                                                                    htmlentitydefs.name2codepoint[
                                                                                                    text[1:-1]])
                                                                                            except KeyError:
                                                                                                pass
                                                                                            return text # leave as is

                                                                                            def text(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def fixup(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            return re.sub("&#?\w+;",
                                                                                                fixup, text)


                                                                                            def safe_urlencode(params,
                                                                                                               doseq=0):
                                                                                                """
        UTF-8-safe version of safe_urlencode

        The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values
        which can't fail down to ascii.
        """
                                                                                                if hasattr(params,
                                                                                                    "items"):

                                                                                                def params():
                                                                                                    """

                                                                                    """
                                                                                                    pass


                                                                                                def params():
                                                                                                    """

                                                                                    """
                                                                                                    pass

                                                                                                params = params.items()

                                                                                                new_params = list()

                                                                                                for k, v in params:
                                                                                                    k = k.encode(
                                                                                                        "utf-8")

                                                                                                    if isinstance(v,
                                                                                                        basestring):
                                                                                                        new_params.append(
                                                                                                            (k,
                                                                                                             v.encode(
                                                                                                                 "utf-8")))
                                                                                                    elif isinstance(v,
                                                                                                        (list, tuple)):
                                                                                                        new_params.append(
                                                                                                            (k,
                                                                                                             [i.encode(
                                                                                                                 "utf-8")
                                                                                                              for i in
                                                                                                              v]))
                                                                                                    else:
                                                                                                        new_params.append(
                                                                                                            (k, unicode(
                                                                                                                v)))

                                                                                            def doseq(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            return urllib.urlencode(
                                                                                                new_params, doseq)


                                                                                            class SolrError(Exception):
                                                                                                pass


                                                                                            class Results(object):
                                                                                                def


                                                                                                def hits(self):
                                                                                                    """

                                                                                    """
                                                                                                    pass


                                                                                                def docs(self):
                                                                                                    """

                                                                                    """
                                                                                                    pass

                                                                                                __init__(self, docs,
                                                                                                    hits,
                                                                                                    highlighting=None,
                                                                                                    facets=None,
                                                                                                    spellcheck=None,
                                                                                                    stats=None,
                                                                                                    qtime=None
                                                                                                    , debug=None):
                                                                                                self.docs = docs
                                                                                                self.hits = hits
                                                                                                self.highlighting = highlighting or {}
                                                                                                self.facets = facets or {}
                                                                                                self.spellcheck = spellcheck or {}
                                                                                                self.stats = stats or {}
                                                                                                self.qtime = qtime
                                                                                                self.debug = debug or {}

                                                                                            def __len__(self):
                                                                                                return len(self.docs)

                                                                                            def __iter__(self):
                                                                                                return iter(self.docs)


                                                                                            class Solr(object):
                                                                                                def


                                                                                                def url(self):
                                                                                                    """

                                                                                    """
                                                                                                    pass


                                                                                                def self(self):
                                                                                                    """

                                                                                    """
                                                                                                    pass

                                                                                                __init__(self, url,
                                                                                                    decoder=None,
                                                                                                    timeout=60):
                                                                                                self.decoder = decoder or json.JSONDecoder()
                                                                                                self.url = url

                                                                                            def url(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def url(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            self.scheme, netloc, path, query, fragment = urlsplit(
                                                                                                url)

                                                                                            def netloc(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def netloc(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            self.base_url = urlunsplit(
                                                                                                (
                                                                                                self.scheme, netloc, '',
                                                                                                '', ''))

                                                                                            def netloc(param):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def netloc(param):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            netloc = netloc.split(':')
                                                                                            self.host = netloc[0]
                                                                                            if len(netloc) == 1:
                                                                                                self.host, self.port =
                                                                                                netloc[0], None
                                                                                            else:

                                                                                            def netloc(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def netloc(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            self.host, self.port =
                                                                                            netloc[0], int(
                                                                                                netloc[1])

                                                                                            def path(param):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def path(param):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            self.path = path.rstrip('/')
                                                                                            self.timeout = timeout


                                                                                    def self():
                                                                                        """

                                                                        """
                                                                                        pass


                                                                                    def self():
                                                                                        """

                                                                        """
                                                                                        pass

                                                                                    self.log = self._get_log()

                                                                                    def _get_log(self):
                                                                                        return LOG


                                                                                    def _send_request(self, method, path
                                                                                                      , body=None,
                                                                                                      headers=None):
                                                                                        if TIMEOUTS_AVAILABLE:


                                                                                        def self(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def self(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        http = Http(
                                                                                            timeout=self.timeout)
                                                                                        url = self.base_url + path

                                                                                        try:
                                                                                            start_time = time.time()

                                                                                        def body(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def method(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Starting request to '%s' (%s) with body '%s'..." % (
                                                                                                url, method,
                                                                                                str(body)[:10]))

                                                                                        def headers(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def headers(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        headers, response = http.request(
                                                                                            url,
                                                                                            method=method,
                                                                                            body=body, headers=headers)
                                                                                        end_time = time.time()

                                                                                        def body(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def method(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.info(
                                                                                            "Finished '%s' (%s) with body '%s' in %0.3f seconds." % (
                                                                                                url, method,
                                                                                                str(body)[:10],
                                                                                                end_time - start_time))
                                                                                        except var = AttributeError
                                                                                        :
                                                                                        # For httplib2.
                                                                                        error_message = "Failed to connect to server at '%s'. Are you sure '%s' is correct? Checking it in a browser might help..." % (
                                                                                            url, self.base_url)

                                                                                        def self(error_message):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.error(error_message)
                                                                                        raise SolrError(error_message)

                                                                                        if int(
                                                                                            headers['status']) != 200:
                                                                                            def response(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                        def response(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        error_message = self._extract_error(
                                                                                            headers,
                                                                                            response)

                                                                                        def self(error_message):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.error(error_message)

                                                                                        def SolrError(error_message):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        raise SolrError(error_message)

                                                                                        return response
                                                                                        else:
                                                                                        if headers is None:
                                                                                            headers = {}

                                                                                        def self(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def self(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        conn = HTTPConnection(self.host,
                                                                                            self.port)
                                                                                        start_time = time.time()

                                                                                        def body(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def method(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Starting request to '%s:%s/%s' (%s) with body '%s'..." % (
                                                                                                self.host, self.port,
                                                                                                path, method,
                                                                                                str(body)[:10]))

                                                                                        def body(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def path(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        conn.request(method, path, body,
                                                                                            headers)

                                                                                        def conn():
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def conn():
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        response = conn.getresponse()
                                                                                        end_time = time.time()

                                                                                        def body(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def method(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.info(
                                                                                            "Finished '%s:%s/%s' (%s) with body '%s' in %0.3f seconds." % (
                                                                                                self.host, self.port,
                                                                                                path, method,
                                                                                                str(body)[:10],
                                                                                                end_time - start_time))

                                                                                        if response.status != 200:

                                                                                        def response():
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def response():
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        error_message = self._extract_error(
                                                                                            dict(response.getheaders()),
                                                                                            response.read())

                                                                                        def self(error_message):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        self.log.error(error_message)

                                                                                        def SolrError(error_message):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        raise SolrError(error_message)

                                                                                        def response():
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        return response.read()

                                                                                        def _select(self, params):
                                                                                            # specify json encoding of results
                                                                                            params['wt'] = 'json'


                                                                                        def params_encoded(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def params(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        params_encoded = safe_urlencode(
                                                                                            params, True)

                                                                                        if len(params_encoded) < 1024:
                                                                                            # Typical case.
                                                                                            path = '%s/select/?%s' % (
                                                                                                self.path,
                                                                                                params_encoded)

                                                                                        def self(param, path):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        return self._send_request('GET',
                                                                                            path)
                                                                                        else:
                                                                                        # Handles very long queries by submitting as a POST.
                                                                                        path = '%s/select/' % (
                                                                                        self.path,)
                                                                                        headers = {
                                                                                            'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'
                                                                                            ,
                                                                                            }

                                                                                        def params_encoded(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def self(param, path, body,
                                                                                                 headers):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        return self._send_request('POST'
                                                                                            , path,
                                                                                            body=params_encoded,
                                                                                            headers=headers)

                                                                                        def _mlt(self, params):
                                                                                            params[
                                                                                            'wt'] = 'json' # specify json encoding of results


                                                                                        def params(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def params(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        path = '%s/mlt/?%s' % (
                                                                                            self.path,
                                                                                            safe_urlencode(params,
                                                                                                True))

                                                                                        def self(param, path):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        return self._send_request('GET',
                                                                                            path)

                                                                                        def _suggest_terms(self,
                                                                                                           params):
                                                                                            params[
                                                                                            'wt'] = 'json' # specify json encoding of results


                                                                                        def params(args):
                                                                                            """

                                                                            """
                                                                                            pass


                                                                                        def params(args):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        path = '%s/terms/?%s' % (
                                                                                            self.path,
                                                                                            safe_urlencode(params,
                                                                                                True))

                                                                                        def self(param, path):
                                                                                            """

                                                                            """
                                                                                            pass

                                                                                        return self._send_request('GET',
                                                                                            path)

                                                                                        def _update(self, message,
                                                                                                    clean_ctrl_chars=True
                                                                                                    ,
                                                                                                    commit=True,
                                                                                                    waitFlush=None,
                                                                                                    waitSearcher=None):
                                                                                            """
    Posts the given xml message to http://<host>:<port>/solr/update and
    returns the result.

    Passing `sanitize` as False will prevent the message from being cleaned
    of control characters (default True). This is done by default because
    these characters would cause Solr to fail to parse the XML. Only pass
    False if you're positive your data is clean.
    """
                                                                                            global children, BeautifulSoup, server_type, value, self
                                                                                            path = '%s/update/' % self.path

                                                                                            # Per http://wiki.apache.org/solr/UpdateXmlMessages, we can append a
                                                                                            # ``commit=true`` to the URL and have the commit happen without a
                                                                                            # second request.
                                                                                            query_vars = []
                                                                                            if commit is not None:


                                                                                            def commit(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            query_vars.append(
                                                                                                'commit=%s' % str(bool(
                                                                                                    commit)).lower())
                                                                                            if waitFlush is not None:

                                                                                            def waitFlush(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            query_vars.append(
                                                                                                'waitFlush=%s' % str(
                                                                                                    bool(
                                                                                                        waitFlush)).lower())
                                                                                            if waitSearcher is not None:

                                                                                            def waitSearcher(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            query_vars.append(
                                                                                                'waitSearcher=%s' % str(
                                                                                                    bool(
                                                                                                        waitSearcher)).lower())
                                                                                            if query_vars:
                                                                                                path = '%s?%s' % (
                                                                                                    path, '&'.join(
                                                                                                        query_vars))


                                                                                            # Clean the message of ctrl characters.
                                                                                            if clean_ctrl_chars:

                                                                                            def message(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def message(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            message = sanitize(message)

                                                                                            def self(param, path,
                                                                                                     message, param1):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            return self._send_request(
                                                                                                'POST', path,
                                                                                                message,
                                                                                                    {
                                                                                                    'Content-type': 'text/xml; charset=utf-8'})

                                                                                            def _extract_error(self,
                                                                                                               headers,
                                                                                                               response):
                                                                                                """
    Extract the actual error message from a solr response.
    """


                                                                                            def headers(param, None):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def headers(param, None):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            reason = headers.get(
                                                                                                'reason', None)
                                                                                            full_html = None

                                                                                            if reason is None:

                                                                                            def response(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def response(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            reason, full_html = self.self._scrape_response(
                                                                                                headers,
                                                                                                response)

                                                                                            msg = "[Reason: %s]" % reason

                                                                                            if reason is None:

                                                                                            def unescape_html(
                                                                                                    full_html):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            msg += "\n%s" % unescape_html(
                                                                                                full_html)

                                                                                            return msg

                                                                                            def _scrape_response(self,
                                                                                                                 headers
                                                                                                                 ,
                                                                                                                 response):
                                                                                                """
    Scrape the html response.
    """
                                                                                                # identify the responding server
                                                                                                server_type = None


                                                                                            def server_string():
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def headers(param, param1):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            server_string = headers.get(
                                                                                                'server', '')

                                                                                            if server_string and 'jetty' in server_string.lower():
                                                                                                server_type = 'jetty'

                                                                                            if server_string and 'coyote' in server_string.lower():
                                                                                                # TODO: During the pysolr 3 effort, make this no longer a
                                                                                                #       conditional and consider using ``lxml.html`` instead.
                                                                                                from BeautifulSoup import BeautifulSoup

                                                                                                server_type = 'tomcat'

                                                                                            reason = None
                                                                                            full_html = ''
                                                                                            dom_tree = None

                                                                                            if server_type == 'tomcat':
                                                                                            # Tomcat doesn't produce a valid XML response

                                                                                            def response(args):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def response(args):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            soup = BeautifulSoup(
                                                                                                response)

                                                                                            def soup(param):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def soup(param):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            body_node = soup.find(
                                                                                                'body')

                                                                                            def body_node(param):
                                                                                                """

                                                                                """
                                                                                                pass


                                                                                            def body_node(param):
                                                                                                """

                                                                                """
                                                                                                pass

                                                                                            p_nodes = body_node.findAll(
                                                                                                'p')

                                                                                            for p_node in p_nodes:
                                                                                                children = p_node.findChildren()

                                                                                                if len(
                                                                                                    children) >= 2 and 'message' in
                                                                                                children[
                                                                                                0].renderContents().lower():
                                                                                            reason = children[
                                                                                                     1].renderContents()

                                                                                        if reason is None:

                                                                                        def soup():
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def soup():
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        full_html = soup.prettify()
                                                                                        else:
                                                                                        # Let's assume others do produce a valid XML response
                                                                                        def response(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def response(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        try:
                                                                                            dom_tree = ET.fromstring(
                                                                                                response)
                                                                                            reason_node = None

                                                                                            # html page might be different for every server
                                                                                            if server_type == 'jetty':
                                                                                                reason_node = dom_tree.find(
                                                                                                    'body/pre')

                                                                                            if reason_node is not None:
                                                                                                reason = reason_node.text

                                                                                            if reason is None:

                                                                                            def dom_tree(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def dom_tree(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            full_html = ET.tostring(
                                                                                                dom_tree)
                                                                                            except var = SyntaxError, e
                                                                                            :
                                                                                            full_html = "%s" % response

                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        full_html = full_html.replace(
                                                                                            '\n', '')

                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        full_html = full_html.replace(
                                                                                            '\r', '')

                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        full_html = full_html.replace(
                                                                                            '<br/>', '')

                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def full_html(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        full_html = full_html.replace(
                                                                                            '<br />', '')

                                                                                        def full_html():
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def full_html():
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        full_html = full_html.strip()
                                                                                        return reason, full_html

                                                                                        # Conversion #############################################################

                                                                                        def _from_python(self, value):
                                                                                            """
    Converts python values to a form suitable for insertion into the xml
    we send to solr.
    """
                                                                                            if hasattr(value,
                                                                                                'strftime'):

                                                                                            def value():
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def value():
                                                                                                """

                                                                                    """
                                                                                                pass

                                                            if hasattr(value, 'hour'):
                                                                                                value = "%sZ" % value.isoformat()
                                                                                            else:
                                                                                                value = "%sT00:00:00Z" % value.isoformat()
                                                                                            elif isinstance(value,
                                                                                                bool)
                                                                                            if value:
                                                                                                value = 'true'
                                                                                            else:
                                                                                                value = 'false'

                                                            elif isinstance(value, str)
                                                                                        def value(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def value(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        value = unicode(value,
                                                                                            errors='replace')
                                                                                        else:
                                                                                        def value(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def value(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        value = unicode(value)
                                                                                        return value

                                                                                        def _to_python(self, value):
                                                                                            """
    Converts values from Solr to native Python values.
    """
                                                                                            global server_type, BeautifulSoup, server_type, path, headers, path, headers, response, headers, headers, SolrError, e, e, file_obj, file_obj, extractOnly, file_obj, waitFlush, commit, m, waitFlush, commit, m, end_time, key, boost, v, boost, docs, commitWithin, params, reason, reason, reason, value, value, value, value, value
                                                                                            if isinstance(value,
                                                                                                (int, float, long,
                                                                                                 complex)):

                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            return value

                                                                                            if isinstance(value,
                                                                                                (list, tuple)):
                                                                                                value = value[0]

                                                                                            if value == 'true':
                                                                                                return True
                                                                                            elif value == 'false':

                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            return False

                                                                                            if isinstance(value,
                                                                                                basestring):

                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def DATETIME_REGEX(value):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            possible_datetime = DATETIME_REGEX.search(
                                                                                                value)

                                                                                            if possible_datetime:

                                                                                            def possible_datetime():
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def possible_datetime():
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            date_values = possible_datetime.groupdict()

                                                                                            def dv(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def dv(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            for dk, dv in date_values.items():
                                                                                                date_values[dk] = int(
                                                                                                    dv)

                                                                                            return datetime(
                                                                                                date_values['year'],
                                                                                                date_values['month'],
                                                                                                date_values['day'],
                                                                                                date_values['hour'],
                                                                                                date_values['minute'],
                                                                                                date_values['second'])

                                                                                            def converted_value(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            try:
                                                                                                # This is slightly gross but it's hard to tell otherwise what the
                                                                                                # string's original type might have been. Be careful who you trust.
                                                                                                converted_value = eval(
                                                                                                    value)

                                                                                                # Try to handle most built-in types.
                                                                                                if isinstance(
                                                                                                    converted_value, (
                                                                                                        list, tuple, Set
                                                                                                        , dict, int,
                                                                                                        float, long,
                                                                                                        complex)):
                                                                                                    return converted_value
                                                                                            except:
                                                                                                # If it fails (SyntaxError or its ilk) or we don't trust it,
                                                                                                # continue on.
                                                                                                pass

                                                                                            return value

                                                                                            def _is_null_value(self,
                                                                                                               value):
                                                                                                """
        Check if a given value is ``null``.

        Criteria for this is based on values that shouldn't be included
        in the Solr ``add`` request at all.
        """
                                                                                                # TODO: This should probably be removed when solved in core Solr level?


                                                                                        def value(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        return (value is None) or (
                                                                                            isinstance(value,
                                                                                                basestring) and len(
                                                                                                value) == 0)

                                                                                        # API Methods ############################################################

                                                                                        def search(self, q, **kwargs):
                                                                                            """Performs a search and returns the results."""
                                                                                            params = {'q': q}


                                                                                        def kwargs(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        params.update(kwargs)

                                                                                        def params(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def params(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        response = self._select(params)

                                                                                        # TODO: make result retrieval lazy and allow custom result objects
                                                                                        def response(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def response(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        result = self.decoder.decode(
                                                                                            response)
                                                                                        result_kwargs = {}

                                                                                        if result.get('debug'):
                                                                                            result_kwargs['debug'] =
                                                                                            result['debug']

                                                                                        if result.get('highlighting'):
                                                                                            result_kwargs[
                                                                                            'highlighting'] = result[
                                                                                                              'highlighting']

                                                                                        if result.get('facet_counts'):
                                                                                            result_kwargs['facets'] =
                                                                                            result[
                                                                                            'facet_counts']

                                                                                        if result.get('spellcheck'):
                                                                                            result_kwargs[
                                                                                            'spellcheck'] = result[
                                                                                                            'spellcheck']

                                                                                        if result.get('stats'):
                                                                                            result_kwargs['stats'] =
                                                                                            result['stats']

                                                                                        if 'QTime' in result.get(
                                                                                            'responseHeader',
                                                                                                {}):
                                                                                            result_kwargs['qtime'] =
                                                                                            var =
                                                                                            result['responseHeader'][
                                                                                            'QTime']

                                                                                        def self(param):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Found '%s' search results." %
                                                                                            result['response'][
                                                                                            'numFound'])

                                                                                        def Results(param, param1,
                                                                                                    param2):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        return Results(
                                                                                            result['response']['docs'],
                                                                                            result['response'][
                                                                                            'numFound'],
                                                                                            **result_kwargs)

                                                                                        def more_like_this(self, q,
                                                                                                           mltfl,
                                                                                                           **kwargs):
                                                                                            """
    Finds and returns results similar to the provided query.

    Requires Solr 1.3+.
    """
                                                                                            params = {
                                                                                                'q': q,
                                                                                                'mlt.fl': mltfl,
                                                                                                }


                                                                                        def kwargs(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        params.update(kwargs)

                                                                                        def params(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def params(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        response = self._mlt(params)

                                                                                        def self(response):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        result = self.decoder.decode(
                                                                                            response)

                                                                                        if result['response'] is None:
                                                                                            result['response'] = {
                                                                                                'docs': [],
                                                                                                'numFound': 0,
                                                                                                }

                                                                                        def self(param):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Found '%s' MLT results." %
                                                                                            result['response'][
                                                                                            'numFound'])

                                                                                        def Results(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        return Results(
                                                                                            result['response']['docs'],
                                                                                            result['response'][
                                                                                            'numFound'])

                                                                                        def suggest_terms(self, fields,
                                                                                                          prefix,
                                                                                                          **kwargs):
                                                                                            """
    Accepts a list of field names and a prefix

    Returns a dictionary keyed on field name containing a list of
    ``(term, count)`` pairs

    Requires Solr 1.4+.
    """
                                                                                            params = {
                                                                                                'terms.fl': fields,
                                                                                                'terms.prefix': prefix,
                                                                                                }


                                                                                        def kwargs(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        params.update(kwargs)

                                                                                        def params(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def params(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        response = self._suggest_terms(
                                                                                            params)

                                                                                        def response(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def response(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        result = self.decoder.decode(
                                                                                            response)

                                                                                        def result(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def result(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        terms = result.get("terms", {})
                                                                                        res = {}

                                                                                        # in Solr 1.x the value of terms is a flat list:
                                                                                        #   ["field_name", ["dance",23,"dancers",10,"dancing",8,"dancer",6]]
                                                                                        #
                                                                                        # in Solr 3.x the value of terms is a dict:
                                                                                        #   {"field_name": ["dance",23,"dancers",10,"dancing",8,"dancer",6]}
                                                                                        if isinstance(terms,
                                                                                            types.ListType):

                                                                                        def terms(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def terms(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        terms = dict(zip(terms[0::2],
                                                                                            terms[1::2]))

                                                                                        for field, values in terms.iteritems():
                                                                                            tmp = list()

                                                                                            while values:
                                                                                                tmp.append(
                                                                                                    (values.pop(0),
                                                                                                     values.pop(0)))

                                                                                            res[field] = tmp

                                                                                        def self(param, param1):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Found '%d' Term suggestions results."
                                                                                            ,
                                                                                            sum(len(
                                                                                                j) for i, j in res.items()))
                                                                                        return res

                                                                                        def add(self, docs, commit=True,
                                                                                                boost=None,
                                                                                                commitWithin=None,
                                                                                                waitFlush=None,
                                                                                                waitSearcher=None):
                                                                                            """Adds or updates documents. For now, docs is a list of dictionaries
    where each key is the field name and each value is the value to index.
    """
                                                                                            start_time = time.time()


                                                                                        def self(param):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Starting to build add request...")
                                                                                        message = ET.Element('add')
                                                                                        if commitWithin:

                                                                                        def commitWithin(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        message.set('commitWithin',
                                                                                            commitWithin)
                                                                                        for doc in docs:
                                                                                            d = ET.Element('doc')

                                                                                            for key, value in doc.items():
                                                                                                if key == 'boost':
                                                                                                    d.set('boost',
                                                                                                        str(value))
                                                                                                    continue

                                                                                                    # handle lists, tuples, and other iterables

                                                                                        def value(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        if hasattr(value, '__iter__'):
                                                                                            for v in value:

                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def self(value):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            if self._is_null_value(
                                                                                                value):
                                                                                                continue

                                                                                            if boost and v in boost:
                                                                                                if

                                                                                            def boost(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            var = not isinstance(boost,
                                                                                                basestring)
                                                                                            :
                                                                                            def v(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def v(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            boost[v] = str(boost[v])

                                                                                            def v(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def v(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            f = ET.Element('field',
                                                                                                name=key,
                                                                                                boost=boost[v])
                                                                                            else:
                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            f = ET.Element('field',
                                                                                                name=key)

                                                                                            def v(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def v(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            f.text = self._from_python(
                                                                                                v)

                                                                                            def d(f):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            d.append(f)
                                                                                            # handle strings and unicode
                                                                                            else:
                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def self(value):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            if self._is_null_value(
                                                                                                value):
                                                                                                continue

                                                                                            if boost and key in boost:
                                                                                                if

                                                                                            def boost(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            var = not isinstance(boost,
                                                                                                basestring)
                                                                                            :
                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            boost[key] = str(boost[key])

                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            f = ET.Element('field',
                                                                                                name=key,
                                                                                                boost=boost[key])
                                                                                            else:
                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def key(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            f = ET.Element('field',
                                                                                                name=key)

                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def value(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            f.text = self._from_python(
                                                                                                value)

                                                                                            def d(f):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            d.append(f)

                                                                                            def d(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def message(d):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            message.append(d)

                                                                                            def message(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def message(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            m = ET.tostring(message,
                                                                                                encoding='utf-8')
                                                                                            end_time = time.time()

                                                                                        def start_time(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def docs(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        self.log.debug(
                                                                                            "Built add request of %s docs in %0.2f seconds." % (
                                                                                                len(docs),
                                                                                                end_time - start_time))

                                                                                        def waitSearcher(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def waitSearcher(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        response = self._update(m,
                                                                                            commit=commit,
                                                                                            waitFlush=waitFlush,
                                                                                            waitSearcher=waitSearcher)

                                                                                        def delete(self, id=None, q=None
                                                                                                   ,
                                                                                                   commit=True,
                                                                                                   waitFlush=None,
                                                                                                   waitSearcher=None):
                                                                                            """Deletes documents."""
                                                                                            if id is None and q is None:
                                                                                                raise ValueError(
                                                                                                    'You must specify "id" or "q".')
                                                                                            elif id is not None and q is not None:
                                                                                                raise ValueError(
                                                                                                    'You many only specify "id" OR "q", not both.')
                                                                                            elif id is not None:
                                                                                                m = '<delete><id>%s</id></delete>' % id
                                                                                            elif q is not None:
                                                                                                m = '<delete><query>%s</query></delete>' % q


                                                                                        def waitSearcher(args):
                                                                                            """

                                                                                """
                                                                                            pass


                                                                                        def waitSearcher(args):
                                                                                            """

                                                                                """
                                                                                            pass

                                                                                        response = self._update(m,
                                                                                            commit=commit,
                                                                                            waitFlush=waitFlush,
                                                                                            waitSearcher=waitSearcher)

                                                                                        def commit(self, waitFlush=None,
                                                                                                   waitSearcher=None,
                                                                                                   expungeDeletes=None):
                                                                                            """

    """
                                                                                            if expungeDeletes is not None:


                                                                                            def expungeDeletes(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def expungeDeletes(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            msg = '<commit expungeDeletes="%s" />' % str(
                                                                                                bool(
                                                                                                    expungeDeletes)).lower()
                                                                                            else:
                                                                                            msg = '<commit />'

                                                                                            def waitSearcher(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def waitSearcher(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            response = self._update(msg,
                                                                                                waitFlush=waitFlush,
                                                                                                waitSearcher=waitSearcher)

                                                                                            def optimize(self,
                                                                                                         waitFlush=None,
                                                                                                         waitSearcher=None
                                                                                                         ,
                                                                                                         maxSegments=None):
                                                                                                """

                                                                                    """
                                                                                                if maxSegments:
                                                                                                    msg = '<commit maxSegments="%d" />' % maxSegments
                                                                                                else:
                                                                                                    msg = '<commit />'


                                                                                            def waitSearcher(args):
                                                                                                """

                                                                                    """
                                                                                                pass


                                                                                            def waitSearcher(args):
                                                                                                """

                                                                                    """
                                                                                                pass

                                                                                            response = self._update(
                                                                                                '<optimize />',
                                                                                                waitFlush=waitFlush,
                                                                                                waitSearcher=waitSearcher)

                                                                                            def extract(self, file_obj,
                                                                                                        extractOnly=True):
                                                                                                """
    POSTs a file to the Solr ExtractingRequestHandler so rich content can
    be processed using Apache Tika. See the Solr wiki for details:

        http://wiki.apache.org/solr/ExtractingRequestHandler

    The ExtractingRequestHandler has a very simply model: it extracts
    contents and metadata from the uploaded file and inserts it directly
    into the index. This is rarely useful as it allows no way to store
    additional data or otherwise customize the record. Instead, by default
    we'll use the extract-only mode to extract the data without indexing it
    so the caller has the opportunity to process it as appropriate; call
    with ``extractOnly=False`` if you want to insert with no additional
    processing.

    Returns None if metadata cannot be extracted; otherwise returns a
    dictionary containing at least two keys:

        :contents:
                    Extracted full-text content, if applicable
        :metadata:
                    key:value pairs of text strings
    """
                                                                                                global e, e, e, e, params, params, params, params, e, e, file_obj, file_obj, extractOnly, file_obj, waitFlush, commit, m, waitFlush, commit, m, end_time, key, boost, v, boost, docs, commitWithin, self, self, params, self, params, self, self, params
                                                                                                if not POSTER_AVAILABLE:


                                                                                                def file_obj(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                raise RuntimeError(
                                                                                                    "Solr rich content extraction requires `poster` to be installed")

                                                                                                # The poster library unfortunately defaults to mime-type None when
                                                                                                # the file lacks a name and that causes it to send the file contents
                                                                                                # as a gigantic string rather than a separate MIME part, which breaks
                                                                                                # and spews the contents in the Solr request log:
                                                                                                if not hasattr(file_obj,
                                                                                                    "name"):
                                                                                                    raise ValueError(
                                                                                                        "extract() requires file-like objects which have a defined name property")

                                                                                                params = {
                                                                                                    "extractOnly": "true" if extractOnly else "false"
                                                                                                    ,
                                                                                                    "lowernames": "true"
                                                                                                    ,
                                                                                                    "wt": "json",
                                                                                                    # We'll provide the file using its true name as Tika may use that
                                                                                                    # as a file type hint:
                                                                                                    file_obj.name: file_obj
                                                                                                    ,
                                                                                                    }

                                                                                                def params(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def params(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                body_generator, headers = multipart_encode(
                                                                                                    params)

                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                try:
                                                                                                    resp = self._send_request(
                                                                                                        'POST'
                                                                                                        ,
                                                                                                        "%s/update/extract" % self.path
                                                                                                        ,
                                                                                                        "".join(
                                                                                                            body_generator)
                                                                                                        ,
                                                                                                        headers)
                                                                                                except (
                                                                                                IOError, SolrError), e:
                                                                                                    def e(args):
                                                                                                        """

                                                                                            """
                                                                                                        pass

                                                                                                self.log.error(
                                                                                                    "Failed to extract document metadata: %s"
                                                                                                    , e,
                                                                                                    exc_info=e)
                                                                                                raise

                                                                                                def self(param, e):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def resp(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                try:
                                                                                                    data = json.loads(
                                                                                                        resp)
                                                                                                except ValueError, e:
                                                                                                    self.log.error(
                                                                                                        "Failed to load JSON response: %s"
                                                                                                        , e,
                                                                                                        exc_info=e)
                                                                                                    raise

                                                                                                data['contents'] =

                                                                                                def file_obj(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def data(name, None):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                data.pop(file_obj.name,
                                                                                                    None)
                                                                                                data[
                                                                                                'metadata'] = metadata = {}

                                                                                                def file_obj(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def data(param, None):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                raw_metadata = data.pop(
                                                                                                    "%s_metadata" % file_obj.name
                                                                                                    ,
                                                                                                    None)

                                                                                                if raw_metadata:
                                                                                                # The raw format is somewhat annoying: it's a flat list of
                                                                                                # alternating keys and value lists

                                                                                                def raw_metadata():
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def raw_metadata():
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                while raw_metadata:
                                                                                                    metadata[
                                                                                                    raw_metadata.pop()] = raw_metadata.pop()

                                                                                                return data


                                                                                                class SolrCoreAdmin(
                                                                                                    object):
                                                                                                    """
    Handles core admin operations: see http://wiki.apache.org/solr/CoreAdmin

    Operations offered by Solr are:
       1. STATUS
       2. CREATE
       3. RELOAD
       4. RENAME
       5. ALIAS
       6. SWAP
       7. UNLOAD
       8. LOAD (not currently implemented)
    """

                                                                                                    def __init__(self,
                                                                                                                 url,
                                                                                                                 *args,
                                                                                                                 **kwargs):
                                                                                                        super(
                                                                                                            SolrCoreAdmin
                                                                                                            ,
                                                                                                            self).__init__(
                                                                                                            *args,
                                                                                                            **kwargs)
                                                                                                        self.url = url

                                                                                                    def _get_url(self,
                                                                                                                 url,
                                                                                                                 params=None
                                                                                                                 ,
                                                                                                                 headers=None):
                                                                                                        if not params: params = {}
                                                                                                        if not headers: headers = {}


                                                                                                def headers(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def headers(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                request = urllib2.Request(
                                                                                                    url,
                                                                                                    data=safe_urlencode(
                                                                                                        params),
                                                                                                    headers=headers)
                                                                                                # Let ``socket.error``, ``urllib2.HTTPError`` and ``urllib2.URLError``
                                                                                                # propagate up the stack.
                                                                                                def request(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def request(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                response = urllib2.urlopen(
                                                                                                    request)
                                                                                                return response.read()

                                                                                                def status(self,
                                                                                                           core=None):
                                                                                                    """http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953"""
                                                                                                    params = {
                                                                                                        'action': 'STATUS'
                                                                                                        ,
                                                                                                        }


                                                                                                def core(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                if core is not None:
                                                                                                    params.update(
                                                                                                        core=core)

                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)

                                                                                                def create(self, name,
                                                                                                           instance_dir=None
                                                                                                           ,
                                                                                                           config='solrcofig.xml'
                                                                                                           ,
                                                                                                           schema='schema.xml'):
                                                                                                    """http://wiki.apache.org/solr/CoreAdmin#head-7ca1b98a9df8b8ca0dcfbfc49940ed5ac98c4a08"""
                                                                                                    params = {
                                                                                                        'action': 'STATUS'
                                                                                                        ,
                                                                                                        'name': name,
                                                                                                        'config': config
                                                                                                        ,
                                                                                                        'schema': schema
                                                                                                        ,
                                                                                                        }


                                                                                                def instance_dir(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass


                                                                                                def name(args):
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                if instance_dir is None:
                                                                                                    params.update(
                                                                                                        instanceDir=name)
                                                                                                else:
                                                                                                    params.update(
                                                                                                        instanceDir=instance_dir)

                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)

                                                                                                    def reload(self,
                                                                                                               core):
                                                                                                        """http://wiki.apache.org/solr/CoreAdmin#head-3f125034c6a64611779442539812067b8b430930"""
                                                                                                        params = {
                                                                                                            'action': 'RELOAD'
                                                                                                            ,
                                                                                                            'core': core
                                                                                                            ,
                                                                                                            }


                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)

                                                                                                    def rename(self,
                                                                                                               core,
                                                                                                               other):
                                                                                                        """http://wiki.apache.org/solr/CoreAdmin#head-9473bee1abed39e8583ba45ef993bebb468e3afe"""
                                                                                                        params = {
                                                                                                            'action': 'RENAME'
                                                                                                            ,
                                                                                                            'core': core
                                                                                                            ,
                                                                                                            'other': other
                                                                                                            ,
                                                                                                            }


                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)


                                                                                                def alias(self, core,
                                                                                                          other):
                                                                                                    """
    http://wiki.apache.org/solr/CoreAdmin#head-8bf9004eaa4d86af23d2758aafb0d31e2e8fe0d2

    Experimental feature in Solr 1.3
    """
                                                                                                    params = {
                                                                                                        'action': 'ALIAS'
                                                                                                        ,
                                                                                                        'core': core,
                                                                                                        'other': other,
                                                                                                        }


                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)


                                                                                                def swap(self, core,
                                                                                                         other):
                                                                                                    """http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b"""
                                                                                                    params = {
                                                                                                        'action': 'SWAP'
                                                                                                        ,
                                                                                                        'core': core,
                                                                                                        'other': other,
                                                                                                        }


                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)


                                                                                                def unload(self, core):
                                                                                                    """http://wiki.apache.org/solr/CoreAdmin#head-f5055a885932e2c25096a8856de840b06764d143"""
                                                                                                    params = {
                                                                                                        'action': 'UNLOAD'
                                                                                                        ,
                                                                                                        'core': core,
                                                                                                        }


                                                                                                def self(args):
                                                                                                    """

                                                                                        """
                                                                                                    return self._get_url(
                                                                                                        self.url,
                                                                                                        params=params)


                                                                                                def load(self, core):
                                                                                                    """

                                                                                        """
                                                                                                    raise NotImplementedError(
                                                                                                        'Solr 1.4 and below do not support this operation.')


                                                                                                # Using two-tuples to preserve order.
                                                                                                REPLACEMENTS = (
                                                                                                    # Nuke nasty control characters.
                                                                                                    ('\x00', ''),
                                                                                                    # Start of heading
                                                                                                    ('\x01', ''),
                                                                                                    # Start of heading
                                                                                                    ('\x02', ''),
                                                                                                    # Start of text
                                                                                                    ('\x03', ''),
                                                                                                    # End of text
                                                                                                    ('\x04', ''),
                                                                                                    # End of transmission
                                                                                                    ('\x05', ''),
                                                                                                    # Enquiry
                                                                                                    ('\x06', ''),
                                                                                                    # Acknowledge
                                                                                                    ('\x07', ''),
                                                                                                    # Ring terminal bell
                                                                                                    ('\x08', ''),
                                                                                                    # Backspace
                                                                                                    ('\x0b', ''),
                                                                                                    # Vertical tab
                                                                                                    ('\x0c', ''),
                                                                                                    # Form feed
                                                                                                    ('\x0e', ''),
                                                                                                    # Shift out
                                                                                                    ('\x0f', ''),
                                                                                                    # Shift in
                                                                                                    ('\x10', ''),
                                                                                                    # Data link escape
                                                                                                    ('\x11', ''),
                                                                                                    # Device control 1
                                                                                                    ('\x12', ''),
                                                                                                    # Device control 2
                                                                                                    ('\x13', ''),
                                                                                                    # Device control 3
                                                                                                    ('\x14', ''),
                                                                                                    # Device control 4
                                                                                                    ('\x15', ''),
                                                                                                    # Negative acknowledge
                                                                                                    ('\x16', ''),
                                                                                                    # Synchronous idle
                                                                                                    ('\x17', ''),
                                                                                                    # End of transmission block
                                                                                                    ('\x18', ''),
                                                                                                    # Cancel
                                                                                                    ('\x19', ''),
                                                                                                    # End of medium
                                                                                                    ('\x1a', ''),
                                                                                                    # Substitute character
                                                                                                    ('\x1b', ''),
                                                                                                    # Escape
                                                                                                    ('\x1c', ''),
                                                                                                    # File separator
                                                                                                    ('\x1d', ''),
                                                                                                    # Group separator
                                                                                                    ('\x1e', ''),
                                                                                                    # Record separator
                                                                                                    ('\x1f', ''),
                                                                                                    # Unit separator
                                                                                                    )

                                                                                                def sanitize(data):
                                                                                                    # close query object
                                                                                                    """

                                                                                        """
                                                                                                    query.close()

                                                                                                except var = IOError as var = e
                                                                                                :
                                                                                                # print exception
                                                                                                print e

                                                                                                # close session
                                                                                                def session():
                                                                                                    """

                                                                                        """
                                                                                                    pass

                                                                                                session.close()

                                                                                                except var = IOError as var = e
                                                                                                :
                                                                                                # print exception
                                                                                                print e